任務:創建程式,讀取給定的文本檔案,并將包含給定子字串的所有行列印到另一個文本檔案中。從檔案中讀取的內容應逐行進行。
我的代碼:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(){
string inputFileName = "inputFile.txt"。
string outputFileName = "outputFile.txt";
fstream inputfile;
ofstream outputFile;
inputfile.open(inputFileName.c_str()。
outputFile.open(outputFileName.c_str() )。
字串keyWord。
cout << "請輸入一個關鍵詞:" << endl;
cin >> keyWord。
字串行。
while (getline(inputfile, line)) {
///從每行開始處理。
if(line.find(keyWord) !=string::npos){
outputFile << "包含你的關鍵詞的行:"/span> << "
"/span>
<< line << "
"。
} else; }
cout << "錯誤。輸入的文本沒有提到的單詞。" << endl。
break。
}
cout << "一個輸出檔案已經被創建!"。
}
問題:我可以在第一行找到我正在搜索的單詞。但在下面幾行中卻找不到(在Enter之后。 )!
uj5u.com熱心網友回復:
int found = 0;
while (getline(inputfile, line)) {
///從每行開始處理。
if(line.find(keyWord) !=string::npos){
outputFile << "包含你的關鍵詞的行:"/span> << "
"/span>
<< line << "
"。
found = 1;
}
}
if(found == 0)
{
cout << "錯誤。輸入的文本中沒有提到的單詞。" << endl;
}
uj5u.com熱心網友回復:
我知道這個問題已經被回答了,但是在你需要在一行中處理多個關鍵詞的情況下,你可以使用我下面的示例代碼。
const std::string needle{ "KeyWord" }。
if ( std::fstream file{ R"(PathToYourFileTest.txt)"/span>, std::ios::in } )
{
for ( std::string line; std::getline( file, line ); )
{
std::size_t pos{ line.find( needle ) }。
for ( ; pos != std::string::npos; pos = line.find( needle, pos needle.size( ) ) )
{
std::cout << line.substr( pos, needle.size( ) ) < < '
'。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333763.html
標籤:
上一篇:C 的std::conditional_t不會與std::is_enum_v和std::underlying_type_t一起編譯。
