我是C++的新手,正在嘗試在文件中對2個字(雙精度和三精度)進行字符串搜索並打印找到它們的行。有些行只有「double」這個詞,有些只有「triple」這個詞。逐行讀取文件並輸出第一個顏色
該代碼似乎不會輸出單詞,它只是在循環結尾處打印最後一行。
我忘了補充說我需要打印找到該單詞的行的第一個元素,我可以找到找到該單詞的行,但是,它似乎不打印第一個元素文件。
這是我的代碼。
int main(int argv, char *argc[]){
const string filen("test.txt");
ifstream inFile(filen.c_str());
string line = "";
char IDList[10];
string ID = "";
char* double_word = "double"; // test variable to search in file
char* triple_word = "triple";
stringstream ss;
string word = "";
unsigned int currentLine = 0;
// iterate through each line and check if the words double or triple exist.
while(getline(inFile, line)){
currentLine++;
if (line.find(double_word) != string::npos) {
cout << "found the word \"double\" on line: " << currentLine << endl;
// this part takes the input file and reads the first character of the line i.e. the ID and adds it to the IDList
// string array.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(triple_word) != string::npos){
cout << "found the word \"triple\" on line: " << currentLine << endl;
// now take the id of this file and add it to a different queue.
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else if(line.find(double_word) && line.find(triple_word) != string::npos){
cout << "Found both words double and triple in line: " << currentLine << endl;
while(inFile >> IDList){
cout << "File Id: " << IDList << endl;
inFile.ignore(numeric_limits<streamsize>::max(), ' ');
for(int i=0;i<10;i++){
ss << IDList[i] << endl;
}
word = ss.str();
}
}
else{
cout << "neither word found, moving to next line" << endl;
}
}
inFile.close();
cout << "Id's added to the queue" << word << endl;
return 0;
}
你能請張貼輸入文件(至少一部分),你得到的輸出? –
它只是格式文本文件:6431313 hello。一份雙層巧克力冰沙。 現在我的輸出只是:在第1行找到單詞「double」。 期望的輸出是:在行上找到雙字(lne數)。 Id是:6431313 –