我正在制作一个程序,您可以登录并注册.所有数据都存储在.txt文件中.我目前遇到的问题是,当我尝试从文件中获取所有数据时,我只得到文件的第一行/字符串.我希望得到.txt中的所有内容.这是一些代码:
什么在.txt中:
hello:world
foo:bar
usr:pass
Run Code Online (Sandbox Code Playgroud)
代码(作为测试):
ifstream check;
check.open("UsrInfo.txt");
string dataStr;
getline(check, dataStr);
cout << dataStr;
cout << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
hello:world
Run Code Online (Sandbox Code Playgroud)
我希望输出是什么:
hello:world
foo:bar
usr:pass
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能解决这个问题?谢谢!
小智 5
你需要通过一个循环并逐行读取
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream check ("example.txt");
if (check.is_open())
{
while ( getline (check,line) )
{
cout << line << '\n';
}
check.close();
}
else cout << "Unable to open file";
return 0;
}
Run Code Online (Sandbox Code Playgroud)