读取Txt文件,逐行,在两个列表中存储多个类型,如果存在的话
C++ Reading Txt File, Line by line, storing multiple types in two lists, if present
我最近一直在学习阅读文本文件,并且已经成功地能够读取和存储数据到列表中-然后允许我很好地排序(我正在尝试学习使用列表,而不是vector 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 << "nnCannot open file!nn";
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;
}
您希望将其存储在列表favoritenumber
或者你想把它存储在一个新的文本文件中,比如字符串文件和整数文件?
如果你想要第二个选项
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
如果(! userFile ){cout & lt; & lt;nn无法打开文件nn";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;
}
从文件中读取一行(使用getline
)后,您可以尝试将其解析为3个元素。如果不行,用2个元素再试一次
或者,如果名称不允许以数字开头(如3M…),您可以在第一个字符处peek()
,并确定它是否看起来像一个数字。
相关文章:
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- C++ 将 CIN 值存储到任何类型的数组中
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- 在C++中,如何在变量中正确存储 BYTE 类型?
- 多维数组存储三种不同的数据类型?
- C++在一个映射中存储不同的指针类型(并处理销毁)
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 张量(多维数组)是树前瞻数据的有效存储类型吗?
- 为什么C++不使用集中存储类型信息以实现高效的 RTTI
- 也许 monad:如何避免在 也许实例中存储 T 类型值<T>?
- 具有不同参数类型并存储类型的回调函数
- 在数据库中存储类型为“double”的变量为“DECFLOAT”
- 对象的存储类型,选择什么更好
- 作为参数传递时字符串字面值的存储类型
- 在实现类似std::variant的类时存储类型标记的问题
- 如何存储类型以便以后进行比较
- 从闪电战阵列获取存储类型
- 如何存储
类型的值 - 存储类型并以编程方式将另一个变量强制转换为存储的类型