gpt4 book ai didi

c++ - 在 C++ 中读取行?

转载 作者:太空宇宙 更新时间:2023-11-04 13:45:51 25 4
gpt4 key购买 nike

我有一个文本文件,我需要将其读入代码中的变量。例如,假设 .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';
}
}

关于c++ - 在 C++ 中读取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com