【发布时间】:2014-09-24 22:35:56
【问题描述】:
我有一个文本文件,需要将其读入代码中的变量。例如,假设.txt 文件如下所示:
John
Town
12
Mike
Village
22
其中有一个名字模式,然后是地址,然后是多人的年龄。我发现 (`)
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
我可以打印出文本文件的每一行,但是如何将文本分配给变量呢? 我记得在 Java 中你可以做一些类似的事情
while(there is a next line){
name = something.readline();
address = something.readline();
age = something.readline();
//do something with variables i.e construct new object then
//re-loop to construct new object with next set of data
}
诀窍在于,在调用 readline() 之后,它将在文本文件中向下移动一行,然后将下一个变量分配给下面的文本,依此类推。如何在 C++ 中重新创建它?
【问题讨论】:
-
'std::string name, address, age;' 'getline(我的文件,名称);' 'getline(我的文件,地址);' 'getline(myfile, age);'