繁体   English   中英

将文件读取到由逗号和换行符分隔的向量中

[英]Reading File into Vector Delimited by Comma and New Line

假设我要读取.txt文件并以这种方式设置格式

Max,1979
Wade,1935
Hugh,1983
Eric,1936

这是我正在使用的代码

  1. 读入文件。
  2. 将其存储到string和int的向量中(分别用于名称和年份)

     void calcAges(){ while (getline(infile, line, ',')){ names.push_back(line); years.push_back(line); } } void printNames(){ cout << "\\n\\tDisplaying data...\\n"; for (int i = 0; i < counter; i++){ cout << (i + 1) << ".\\tName: " << names[i] << "\\tYear: " << years[i] << endl; } } 

输出应如下所示:

1.    Name: Max    Year: 1979
.
.
.
and so on...

但是,我在尝试创建它时遇到了麻烦,因此我读入“ infile”的文件以逗号和换行符分隔。 我将这些变量存储到向量数组中,以便稍后进行排序和切换。 在这一点上,我很沮丧。

给定','作为分隔符后,新行将被视为普通字符。 因此,请使用getline()而不指定分隔符(默认为换行符),然后尝试从获取的字符串中提取名称和年份。 使用find_first_of()substr()可以很容易地完成它

例:

while(getline(infile,str))
{
     int index = str.find_first_of(',');
     string name = str.substr(0,index);
     string date = str.substr(index+1);
      // Do something with name and date

}

当涉及到此类操作时, StringStream的功能要强大得多。 但是,在您的情况下(这被认为很简单),您可以通过对字符串的简单操作来摆脱困境。 我建议将每一行读入您的临时字符串,然后在逗号上将其分割,然后将值添加到向量中,如下所示:

void calcAges(){
    while (getline(infile, line)){  // Read a whole line (until it reads a '\n', by default)
        names.push_back(line.substr(0,line.find(",")); // Read from the beginning of the string to the comma, then push it into the vector
        years.push_back(std::stoi(line.substr(line.find(",") + 1)); // Read from the comma to the end of the string, parse it into an integer, then push it into the vector
    }
}

我假设您正在使用<string>库中的std::string作为line变量的类型。

我并没有进行编译和测试,所以我不确定它是否可以正常工作,但是我写它只是为了让您对逻辑方法有所了解

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM