使用fstream和sstream一起从文件中分离字符串/整数

时间:2015-06-06 19:41:28

标签: c++ string filestream stringstream

所以我想从文件中获取信息,它将从名称(字符串)开始,最终将更改为整数。

实施例。对于nums.txt

James Smith
John Jones
Amy Li
1 3 2 3
3 2 4 1 0

我想编写一个程序来存储每个名称(每行一个名称),然后当名称结束并且数字开始时,它会开始将每个#cause添加到数组中。 I.E.如果3 2出现,我想要

numInt[2] to equal 3

我想使用ifstream从文件中获取输入,并使用字符串流对字符串和整数进行排序。到目前为止我有这个

int main() {
 string names[10];
 int numNames = 0;
 int numInt[100] = {};
 ifstream file("nums.txt");
 stringstream ss;
 string s;
 int n;

 while (file >> ss) {
  while (ss >> s) {
   names[numNames] = s;
   numNames++;
  }
  while (ss >> n) {
   numInt[n]++;
  }
 }
 return 0;
}

我知道我犯了这个错误,但我不确定如何正确地做到这一点。

1 个答案:

答案 0 :(得分:2)

我想我会做这样的事情:

Joe Blow
1 2 3
Jerry Coffin

这支持了您所要求的内容,但并未严格执行。 IOW,如果你有类似的东西:

names

......它会让#34; Joe Blow"和Jerry Coffin"在1中的23numbers var cors = new EnabledCorsAttribute("", "", "DataServiceVersion,MaxDataServiceVersion"); config.EnableCors(cors);