读取Txt文件,逐行,在两个列表中存储多个类型,如果存在的话

C++ Reading Txt File, Line by line, storing multiple types in two lists, if present

本文关键字:存储 类型 如果 存在 列表 逐行 文件 Txt 读取 两个      更新时间:2023-10-16

我最近一直在学习阅读文本文件,并且已经成功地能够读取和存储数据到列表中-然后允许我很好地排序(我正在尝试学习使用列表,而不是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(),并确定它是否看起来像一个数字。