我有我需要读给我的代码中的变量的文本文件。 例如让说.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 ++?
当我做这样的东西,我喜欢我的数据结构为记录和写一个函数来读取每个记录,而像这样:
// logically grouped data
struct record
{
std::string name;
std::string address;
unsigned age;
};
// function to read in one record
// returns std:ostream& so that the while() loop can check
// the stream to make sure the read was successful.
// Takes record as a reference to pass the data back out
// of the function
std::istream& read(std::istream& is, record& r)
{
std::getline(is, r.name);
std::getline(is, r.address);
is >> r.age >> std::ws;
return is;
}
int main()
{
std::ifstream myfile("example.txt");
record r;
while(read(myfile, r)) // while the read was a success
{
// do something with record here
std::cout << " name: " << r.name << '\n';
std::cout << "address: " << r.address << '\n';
std::cout << " age: " << r.age << '\n';
std::cout << '\n';
}
}