readline在C ++? [英] readline in C++?
问题描述
我有一个文本文件,我需要读入我的代码中的变量。例如,让我们说 .txt
文件如下:
I have a text file that I need to read in to variables in my code. For example lets say the .txt
file looks like:
John
Town
12
Mike
Village
22
其中有一个名称的模式,然后地址,然后多个人的年龄。我发现有( ` )
where there is a pattern of name then address then age of multiple people. I found that with (`)
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
我可以打印出文本文件的每一行,将文本转换为变量?
我记得在Java中你可以按照
I can print out each line of the text file, but how could I assign the text to a variable? I remember in Java you could do something along the lines of
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()被调用后,它将在文本文件中向下移动一行,然后下一个变量将被分配给下面的文本等等。
the trick was that after readline() was called it would then move down a line in the text file and then next variable would be assign to the text below and so on. How can I recreate this in C++?
推荐答案
当我做这样的事情,我喜欢把我的数据结构成记录和写一个读取每个记录的函数,如下:
When I do stuff like this, I like to structure my data into records and write a function to read each record rather like this:
// 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';
}
}
这篇关于readline在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!