使用不同的行格式从文件中读取和存储日期

时间:2022-04-18 20:18:51

How do I read a file in which each line has a different format. I have a file that looks like this

如何读取每行具有不同格式的文件。我有一个看起来像这样的文件

James 0 14 12  
Lucy    
Lucas 0 45   
Alice 87 23 10 23    
etc...

And I have to store the values to use them later. How would I do that.

我必须存储值以便以后使用它们。我该怎么做

If each line had the same format I would use getline(), but can I use it here?

如果每行都使用相同的格式,我会使用getline(),但我可以在这里使用吗?

1 个解决方案

#1


0  

You can use a stringstream to help separate out your values once you get each line. For example:

获得每一行后,您可以使用字符串流来帮助分离您的值。例如:

std::string line = "James 0 14 12";
std::istringstream ss(line);
std::string piece;
while(ss >> piece)
    std::cout << piece << '\n';

will print out:

将打印出来:

James
0
14
12

You could add each piece to whatever data structure you want.

您可以将每个部分添加到您想要的任何数据结构中。

#1


0  

You can use a stringstream to help separate out your values once you get each line. For example:

获得每一行后,您可以使用字符串流来帮助分离您的值。例如:

std::string line = "James 0 14 12";
std::istringstream ss(line);
std::string piece;
while(ss >> piece)
    std::cout << piece << '\n';

will print out:

将打印出来:

James
0
14
12

You could add each piece to whatever data structure you want.

您可以将每个部分添加到您想要的任何数据结构中。