我正在从文本文件中读取,并且我需要能够访问每个整数,类似于Java使用nextInt()的方式。现在,如果我有一个名为"input"的ifstream和一个INT类型的变量"x",input >> x
将忽略行中所有的空格并给我一个大整数,而不仅仅是给我该行中的第一个整数。
例如,如果我的文本文件看起来像这样:
5 67 8
12 3 4
当我说input >> x
时,x现在的值是"5678"而不是"5",然后下次我调用它时是"67"。
如何解析?
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;
}
include
<标题>包括下面的代码按预期工作:
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;
}
标题>