我正在编写一个程序,该程序从文本文件中读取整数并将其显示在屏幕上。我想使用stringstream,但是我不确定它是如何工作的。
文本文件也包含单词,例如:
She bought a tshirt for 25 shoes for 50 and a book for 5
在屏幕上只能看到25、50和5。现在我看到的输出仅为0。我的代码:
#include <iostream>
#include "std_lib_facilities.h"
using namespace std;
string file = "file.txt";
void f() {
vector<int> num;
ifstream ist {file};
if (!ist) error("can't open input file", file);
string textline;
while (getline(ist, textline)) {
istringstream text(textline);
int integer;
text >> integer;
num.push_back(integer);
}
for (int i = 0; i < num.size(); i++) {
cout << num[i] << endl;
}
}
int main()
{
f();
return 0;
}
是否有可能以其他方式进行?有人可以向我解释吗?
仅当您成功阅读一个数字后才打印数字,并且应逐字阅读,而不是逐行阅读。现在,您只尝试第一个单词,但失败了。
string word;
while (ist >> word) {
istringstream text(word);
int integer;
if (text >> integer)
{
num.push_back(integer);
}
}