C++ C++;从.txt读取所有内容
我正在制作一个你可以登录和注册的程序。所有数据都存储在.txt文件中。我目前的问题是,当我试图从文件中获取所有数据时,我只获取文件的第一行/字符串。我想在.txt中获取所有内容。下面是一些代码: .txt文件中有什么内容:C++ C++;从.txt读取所有内容,c++,C++,我正在制作一个你可以登录和注册的程序。所有数据都存储在.txt文件中。我目前的问题是,当我试图从文件中获取所有数据时,我只获取文件的第一行/字符串。我想在.txt中获取所有内容。下面是一些代码: .txt文件中有什么内容: hello:world foo:bar usr:pass 代码(作为测试): 我希望输出为: hello:world foo:bar usr:pass 我能做些什么来解决这个问题?谢谢 你需要把它放进一个循环,然后逐行阅读 #include <iostrea
hello:world
foo:bar
usr:pass
代码(作为测试):
我希望输出为:
hello:world
foo:bar
usr:pass
我能做些什么来解决这个问题?谢谢 你需要把它放进一个循环,然后逐行阅读
#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;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
弦线;
ifstream检查(“example.txt”);
如果(检查.是否打开())
{
while(getline(check,line))
{
cout你需要把它通过一个循环,逐行阅读
#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;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
弦线;
ifstream检查(“example.txt”);
如果(检查.是否打开())
{
while(getline(check,line))
{
coutgetline得到一行,如果你想要更多的话,试试这个
std::string Line, Result;
while (true){
getline(check, Line);
if (!check.eof())
Result.append(Line), Result.push_back('\n');
else
break;
}
getline获得一行,如果您想要多行,请尝试以下方法
std::string Line, Result;
while (true){
getline(check, Line);
if (!check.eof())
Result.append(Line), Result.push_back('\n');
else
break;
}
可能重复的我只得到第一行
你考虑过对其他行重复同样的操作吗?可能会有帮助。可能重复的我只得到第一行
你考虑过对其他行重复同样的操作吗?可能会有帮助。在这里不会。逗号运算符几乎是cer当然不是你想在这里使用的。应该可以,但是一种非常糟糕的编码风格不值得教或模仿,因为逗号误用会悄悄地破坏程序。只需使用分号。你认为这样可以解决它吗?建议使用while(getline(check,Line))
而不是while(true)
getline
返回对所用iostream的引用,并且iostream实现一个布尔运算符,如果流可读且未处于错误状态,则返回true。Result.append(Line),Result.push_back(“\n”);
从“,”中得不到任何好处。为了清晰起见,请使用“;”或Result.append(Line+“\n”);
不会在这里使用。逗号运算符几乎肯定不是您想要在这里使用的。应该可以使用,但是一种非常糟糕的编码风格不值得教授或模仿,因为逗号误用会悄悄地破坏程序。只需使用分号。您认为这会解决它吗?建议while(getline(check,Line))
而不是while(true)
getline
返回对所用iostream的引用,并且iostream实现一个布尔运算符,如果流可读且未处于错误状态,则返回true。Result.append(Line),Result.push_back('\n');
从“,”中得不到任何好处。为了清晰起见,请使用“;”或结果。追加(行+“\n”);