【问题标题】:How do you read chars from an input file and store them into a vector?你如何从输入文件中读取字符并将它们存储到向量中?
【发布时间】:2019-09-27 01:55:23
【问题描述】:

首先是输入文件:

0 a   a b c 

0 b   d e f 

1 c   g h i 

1 d   j k l 

我们试图从输入文件中读取并将接收到的字符存储到一个向量中,然后从那里将它存储到一个名为T 的二维表中。我们得到了初始的 while 循环,因此它抓取第一列并输出“a b c d”,但我们无法让它返回通过whilefor 循环来抓取其他行和列。以下是我们目前所拥有的:

int readTable() {
  int row, col;  // row and col numbers
  char col_c;    // column indicator
  ifstream fin("C:\\Users\\name\\OneDrive\\Desktop\\lines.txt", ios::in);

  // Read in the file into T
  while (fin >> row)  // next line of file
  {
    fin >> col_c;
    col = convert(col_c);  // convert to a slot number
    vector<char> v;        // a vector to fill
    char c;                // one char from the file
    // ** Fill v with chars from the file (there are VM chars)
    for (int i = 0; i < VM; i++) {
      fin >> c;
      v.push_back(c);
    }
    // ** Put  v in T[row][col]
    T[row][col] = v;

  }  // end of while

convert 函数只是将“a”转换为 0,“b”转换为 1,“c”转换为 2,以便我们将向量放置在 T 中的正确位置。任何有**的地方都应该是我们编辑和修改的部分。

【问题讨论】:

  • 你怎么知道 while 循环不起作用?
  • T 是二维向量数组吗?

标签: c++ visual-studio computer-science


【解决方案1】:

编辑: 正如其他人指出的那样,我的说法是不正确的。我把这个答案留在这里,以防其他人可能有同样的误解。


线

while (fin >> row)

看起来不对。运算符 istream::operator &gt;&gt; 返回流本身,因此您的 while 循环将永远继续。

要修复它,您应该添加类似if (fin.eof()) 的内容来检测文件的结尾。参见例如herethere 了解详细信息和示例。

【讨论】:

  • 他的表达式是测试有效输入的正确方法。而且 cplusplus.com 并不是 C++ 的最佳网站。我会推荐cppreference.com
  • @0x499602D2 你的意思是测试fin是不是0?但除此之外,while 循环无法结束 - 没有 break... 对于 cplusplus 的事情,我只是抓住了 google 给我的第一个链接... 添加了您的建议。
  • while (fin &gt;&gt; row) 返回 fin,然后其 operator bool 用于返回其状态(true:good, false:problem)。这是用于流的惯用 C++。
  • std::istream 已实现 an operator bool 将流转换为布尔值,可以测试该流是否处于错误状态。
  • 我明白了!我想我太老了,赶不上C++ 11...学到了一些新东西。谢谢大家!
猜你喜欢
  • 2021-06-17
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多