[英]C++ Reading Txt File, Line by line, storing multiple types in two lists, if present
我最近一直在学习有关阅读文本文件的知识,并且已经能够成功读取数据并将数据存储到列表中-这样一来,我就可以很好地进行排序了(我试图学习使用列表,而不是Vectors atm,因此请回答使用那将是完美的)。
我的问题是,当textfiles
数据类型发生变化时,结构略有不同-我将提供一个示例:
Joe Smith 15
Eileen Jones 4
Joey 12
James Rush 2
因此,基本上,我正在尝试读取一个数据类型不断变化且长度不确定的文件。 理想情况下,我想将名字和姓氏放在单个字符串中,然后将整数分开-但是也提供了单个字符串存在的范围。
通过搜索,我发现我应该将整行作为字符串,然后使用stringstream
拆分信息-唯一的问题是,如果数据从具有两个字符串更改为仅位于整数之前的一个字符串,则它不会存储。
从那里,我必须将字符串存储在一个列表中,将整数存储在另一个列表中,同时将名字/姓氏存储在一起(如果它们都存在的话)-否则,如果只是一个字符串。
希望这是有道理的。 我一直在寻找几天,只是找不到一种方法。 我真的很感谢您的帮助!
另外,到目前为止,我的代码是:
#include <iostream>
#include <list>
#include <fstream>
using namespace std;
int main()
{
list <string> eachLine;
list <string> personName;
list <int> favouriteNumber;
int intStore;
string strStore;
ifstream userFile("Test.txt");
// check if file is open
if (!userFile)
{
cout << "\n\nCannot open file!\n\n";
cin.get();
return 1;
}
while (!userFile.eof())
{
userFile >> stringStore;
eachLine.push_back(tempStore);
}
// ?????? Split Strings from list (eachLine) - so to have either
// <string>, <string>, <int> or <string>, <int>. Then store
// strings in list1 (personName) and ints in
// list2 (favouriteNumber)
system("pause");
return 0;
}
从文件中读取一行(使用getline
)后,您可以尝试将其解析为3个元素。 如果不起作用,请尝试使用2个元素。
或者,如果名称不允许以数字开头(例如3M ...),则可以在第一个字符处peek()
并确定它是否看起来像数字。
您想将其存储在收藏夹列表中
还是要将其存储在新的文本文件中,例如一个字符串存储在另一个文本文件中?
如果你想要第二个选择
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
如果(!userFile){cout <<“ \\ n \\ n无法打开文件!\\ n \\ n”; cin.get(); 返回1; }
while (!userFile.eof())
{
userFile >> tempStore;
favouriteNumber.push_back(tempStore);
}
ifstream userFile("Test.txt");
list <int> favouriteNumber;
oftream userF;
userF.open("INTEGERS.txt");
userF << favouriteNumber;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.