无法从文件中读取下一行
Trouble reading next line from a file
我正在尝试制作一个 C++ 程序,该程序在文本文件中查找特定行,然后读取该文件的下 3 行。但是该程序最终显示相同的第三行 times.What 可能是解决此问题的方法吗?这是我的代码-
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("file.txt");
string line;
int iffound=0;
string inp;
cin>>inp;
cout << "You have searched for " << inp << endl;
while (file.good())
{
getline(file,line);
if(line==inp){
iffound=1;
cout << "Contact Found!" << endl;
for(int i=0;i<=2;i++){
cout << line;
}
break;
}
}
file.close();
if(iffound!=1){
cout << "Contact Not Found" << endl;
}
return 0;
}
这是我的文本文件 (file.txt)
123456
User1
Available
Active
789456
User2
Not Available
Active
好吧,如果你发现了你的出现,你就不会用 getline
阅读以下两行。基本上,您缺少 for
中的 getline
你的内部循环不再读取,它只打印 3 次:
for(int i=0;i<=2;i++){
cout << line;
}
如果您希望代码继续阅读更多行,您也需要将阅读内容放入该循环中:
for(int i=0;i<=2;i++){
getline(file,line);
cout << line;
}
我正在尝试制作一个 C++ 程序,该程序在文本文件中查找特定行,然后读取该文件的下 3 行。但是该程序最终显示相同的第三行 times.What 可能是解决此问题的方法吗?这是我的代码-
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("file.txt");
string line;
int iffound=0;
string inp;
cin>>inp;
cout << "You have searched for " << inp << endl;
while (file.good())
{
getline(file,line);
if(line==inp){
iffound=1;
cout << "Contact Found!" << endl;
for(int i=0;i<=2;i++){
cout << line;
}
break;
}
}
file.close();
if(iffound!=1){
cout << "Contact Not Found" << endl;
}
return 0;
}
这是我的文本文件 (file.txt)
123456
User1
Available
Active
789456
User2
Not Available
Active
好吧,如果你发现了你的出现,你就不会用 getline
阅读以下两行。基本上,您缺少 for
getline
你的内部循环不再读取,它只打印 3 次:
for(int i=0;i<=2;i++){
cout << line;
}
如果您希望代码继续阅读更多行,您也需要将阅读内容放入该循环中:
for(int i=0;i<=2;i++){
getline(file,line);
cout << line;
}