如何在c++中从文件中读取string和相应的int

How to read string and corresponding int from a file in C++?

本文关键字:int string 文件 c++ 读取      更新时间:2023-10-16

我正在做一个由两部分组成的课程项目,已经完成了第一部分,但在第二部分遇到了麻烦。在第一部分中,我能够从文件中读取一个列表,并将其读取到一个向量中,以便使用各种函数进行操作。这个部分的列表看起来像:

banana
apple
pineapple
grapefruit
orange
pear
grape
lime
lemon

我能够完成。对于第一部分,我有一个字符串向量。然而,第二部分为这些值引入了一个量。这个部分的列表如下:

foo 5
bar 4
baz 2
boz 1
foo 3

在这一点上,我不确定如何读取item作为字符串和后面相应的int。对于重复的项,它们应该加到该项的原始值上。我计划有一个对象的矢量,它有一个名称和一个数量来操纵,但我需要先读取文件。谢谢你的帮助!

这是我最初读取文件

的方式
if (fileIn.is_open()){
//file opened successfully so we are here 

    ifstream inf(fileName + ".txt");
    string word;
    while (inf >> word)
    {
        currentSet.push_back(word);
    }

就这样做:

map<string, int> vals; //or some other data structure
ifstream ifs(somefile);
string word;
int i;
while(ifs >> word >> i) {
  vals[word] += i;
}

简单地一个接一个地读。当然,您可以根据需要添加错误检查。但是我推荐使用map数据结构,以便于访问和操作。