首页 文章

使用getline在文件中读取时将值迭代到向量中

提问于
浏览
2

我正在尝试创建一个矢量,其中填充了'blokus tiles'文件的每个字符串行的大小值(尺寸为5x5的句点或星形的图块) . 该文件作为字符串向量的向量读入,

vector <std::string> tile 
vector <vector<string>> alltiles

我正在尝试将值迭代到一个存储tile字符串(每行)大小的向量中 . 如果每条线的长度不同,或者每条线的长度不正确,或者除了星号(*)或句点( . )之外还有其他字符,我这样做是为了稍后输出错误 . 我这样做是为了在文件blokusstatus.txt(作为命令行参数输入)中打印tile的大小,

if (infile.is_open()) {
   while (std::getline(infile, tileline)) {   
     int actualtilesize = tileline.length();
     cout << actualtilesize << std::endl;

     tile.push_back(tileline);
     alltiles.push_back(tile); 
   }
  }
  infile.close();

//print out the contents of the file
  std::ofstream outfile;
  outfile.open(arginfile); 
  for (auto e: tile) { 
    cout << e << std::endl; 
  }

结果如下:

ec327@ec327-VirtualBox:~$ ./w5blokus2 5 blokusstatus.txt
5
5
5
5
5
0
5
5
5
5
5
0
5
5
5
5
5
.....
.*...
**...
*....
*....

.....
.....
**...
*....
**...

.....
.....
*....
***..
*....

这看起来不错 . 但是,我尝试以这种方式将数字列表转换为向量:

if (infile.is_open()) {   //infile is open only if 3 or 4 arguments
  int i = 0;
  while (std::getline(infile, tileline)) {
    for (int i=0; i <= tileline.end(); i++) {   
      vector <int> sizenums;
      sizenums[i] = tileline.length();
      i++;
      cout << sizenums << std::endl;
    }
    //cout << actualtilesize << std::endl;
  }
  tile.push_back(tileline);
  alltiles.push_back(tile); 
}
infile.close();

std::ofstream outfile;
outfile.open(arginfile);  
for (auto e: tile) { 
  cout << e << std::endl; 
}

这在编译时会产生很长的错误,包括

^ ~~~~~~~ / usr / include / c / 6 / ostream:497:5:注意:模板参数/替换失败:w5blokus3.cpp:80:15:注意:推导出参数'_CharT'的冲突类型('char'和'std :: vector')cout << sizenums << std :: endl;“w5blokus3.cpp:80:15:注意:无法将'sizenums'(类型'std :: vector')转换为类型'char'cout << sizenums << std :: endl;

而且我不确定是什么问题 . 我是新手,感谢任何帮助或提示 .

2 回答

  • 0
    for (int i=0; i <= tileline.end(); i++) {   
       vector <int> sizenums;
       sizenums[i] = tileline.length();
    

    首先,通过循环每次迭代创建一个新向量 . 您需要创建向量,然后循环或迭代它 .

    然而,之后

    vector<int> sizenums;
    

    你的矢量是空的 . []的直接访问不起作用 . 使用push_back将元素添加到结尾:

    vector <int> sizenums;
    ...
    for (int i=0; i <= tileline.end(); i++) {  
        sizenums.push_back(tileline.length());
    

    也:

    for(int i ...
         ...
         i++;
    

    不要手动增加循环变量 . for循环已经处理了 .

  • 0

    有两件事,你需要遍历向量来打印出它的内容,你不能使用 sizenums[i] = tileline.length(); 因为向量刚刚被初始化,你必须使用像_809040这样的东西,但是再次按照're using it is wrong anyway, you'重新初始化变量的方式你循环的时间,因此你知道为什么再把 i++; 放在那里,似乎没必要 .

相关问题