【问题标题】:Parse integers separated by spaces rather than line by line - C++解析由空格分隔的整数而不是逐行 - C++
【发布时间】:2016-11-08 02:57:18
【问题描述】:

我正在从文本文件中读取数据,并且我需要能够访问每个整数,类似于 Java 使用 nextInt() 的方式。现在,如果我有一个名为“input”的 ifstream 和一个 INT 类型的变量“x”,input >> x 将忽略行中的所有空格并给我一个大整数,而不是只给我第一个整数线。

例如,如果我的文本文件如下所示:

5 67 8
12 3 4

当我说input >> x 时,x 现在的值是“5678”,而不仅仅是“5”,下次我调用它时又是“67”。

我该如何解析?

【问题讨论】:

  • 我很确定你弄错了。 operator>> 不能那样工作。
  • @SamVarshavchik 我编辑了我的帖子以更好地展示我的文本文件的外观。这就是解析为我工作的方式。我正在打印我的数字以检查它是如何工作的。
  • 不,这仍然不是operator>> 的工作方式。
  • 1.当问题是关于 C++ 时,为什么要标记 java? 2.cin不读取空格
  • 请显示更多您的代码。

标签: java c++ parsing


【解决方案1】:

mgl@mgl:~/Documents$ cat int_file.log

45 20 12 45 21 25

#include <string>
#include <iostream>
#include <fstream>  
#include <vector> 
using namespace std;
int main(){
    vector<int> words;
    ifstream in("int_file.log");
    int word;
    while( in >> word)
    words.push_back(word);

for(int i = 0; i < words.size();i++)
cout << words[i] << endl;

return 0;
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

    包括

    包括

    以下代码按预期工作:

    int main() {
        std::ifstream input ("test.txt", std::ifstream::in);
        int x, y, z;
    
        input >> x;
        input >> y;
        input >> z;
    
        std::cout << "x = " << x << " y = " << y << " z = " << z << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2021-02-17
      相关资源
      最近更新 更多