首页 > 解决方案 > ifstream 其他行中的不同数据类型

问题描述

几周前我刚刚开始使用 C++,需要一些帮助来完成我的“作业”。

我需要阅读:

row1: int int
row2: int char

从文本文件。我的代码如下所示:

int main() {
  [...]
  ifstream fin(argv[1]);
  int i{0}, tmp;
  while (fin >> tmp) {
    cout << pos << "zahl" << tmp << endl;
    if (pos == 0) {
      wagen = tmp;
    }  // needed for an array
    if (pos == 1) {
      reihen = tmp;
    }
    i++;
    [...] return 0;
  }

我的问题是你如何解决row2+?我尝试了类型转换并在谷歌上搜索了一个多小时,但没有发现任何有用的东西。

标签: c++

解决方案


没有什么能阻止你拥有这样的结构。您只需在循环之外阅读:

int x, y;
std::cin >> x >> y;

int val; 
char c;


while (!std::cin.eof())  /* while the end of the stream has 
                          * not been reached yet */
{
  int val;
  std::cin >> val;

  /* getting characters from a stream is tricky; consider a line such
   * as "123    c\n"; you read the int, 123, but then when you read the
   * character, you'll want the 'c', not a whitespace character, so
   * "std::cin >> std::ws" consumes the "leading" whitespace before the
   * character. */
  char c = (std::cin >> std::ws).get();

  /* next step is to ignore the trailing whitespace on the current line */
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

编辑:可能需要一些解释,所以我在代码注释中添加了它。

PS我自己没有测试过代码。


推荐阅读