循环后如何继续阅读
How to keep reading after while loop?
我有一个.txt文件,它的第一行有一个数字和空格序列,我希望读取到向量中。然后在下一行有一个"$"符号。在这之后的一行是另一行,包含一系列数字和空格(就像第一行(,我想把它们读入另一个向量。例如
1 2 3 4 5$4 3 2 1 6
我已经尝试了所有的方法,但在初始while循环读取整数后无法继续读取。我如何越过第二行,读第三行?现在它只输出第一行。目前,这是我的代码:
int main(int argc, const char * argv[]) {
ifstream file(argv[1]);
if (file.is_open() && file.good()){
int addMe;
vector<int> addMeList;
while(file>>addMe){
cout <<addMe<<endl;
addMeList.push_back(addMe);
}
string skip;
while(file >> skip)
cout << skip << endl;
int searchQuery;
vector<int> searchQueries;
while(file>>searchQuery){
searchQueries.push_back(searchQuery);
}
for (int i=0; i<searchQueries.size();i++)
{
cout << searchQueries[i]<<endl;
}
}
return 0;
}
两个问题:
-
第一个循环将导致流
failbit
被设置(当它试图从第二行读取'$'
时(。如果设置了该位,则无法从流中读取更多内容。你需要以清除流状态。 -
完成上述操作后,第二个循环将读取文件的其余部分。
一种可能的解决方案是读取行。使用例如std::getline
读取一行。将该行放入std::istringstream
中,并从中读取值。
程序逻辑似乎有缺陷。使用第一个while
循环,您逐字逐句地读取整个文件,直到最后(而不是行尾(,之后尝试再次读取失败,评估为false
,因此它甚至从未进入其他循环。相反,考虑使用getline
逐行读取,然后使用istringstream
将其分解为int
以下是我改进它的方法:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream> // include this header to use istringstream
using namespace std;
int main() {
ifstream file("text.txt"); // my test file; Replace with yours
if (file.is_open() && file.good()) {
string lineIn; // general line to read into
int i; // general int to read into
vector<int> addMeList;
// int addMe; // not needed anymore
getline(file, lineIn); // read a line 1
istringstream istr(lineIn); // string stream we can use to read integers from
while (istr >> i) {
cout << i << endl;
addMeList.push_back(i);
}
// string skip; // not needed anymore
getline(file, lineIn); // skips line 2
// int searchQuery; // not needed anymore
vector<int> searchQueries;
getline(file, lineIn); // read a line 2
istringstream istr2(lineIn); // string stream we can use to read integers from
while (istr2 >> i) {
searchQueries.push_back(i);
}
for (int i = 0; i < searchQueries.size(); i++)
{
cout << searchQueries[i] << endl;
}
}
return 0;
}
输入文件:
1 2 3 4 5
$
4 3 2 1 6
输出:
1
2
3
4
5
4
3
2
1
6
相关文章:
- 循环后如何继续阅读
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- C++:继续创建新的变量可以吗
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 在 c++ 中三元运算符中不允许继续(关键字)吗?
- C++ 如何暂停控制台输出,以便用户可以在继续之前阅读信息
- 循环不继续无法弄清楚为什么
- 附加到 gdb 会中断并且不会继续该过程
- C++ 在信号处理程序后继续执行
- 为什么我的Qt程序在断言失败后继续运行?
- 如何打印下一个字母直到 Z 并继续到 A?
- 超时后,线程睡眠不会继续执行
- 使用 ssh 重新连接到远程 Ubuntu 机器后,如何继续使用 gdb 调试 c++ 代码?
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- 失败后可以继续从流读取吗?
- 在构造函数中删除后继续执行
- 在程序继续C++时保持进程运行
- 继续运行程序而无需任何干预,直到要求退出为止
- while 循环 C++ 结束,但不继续到其余语句
- C++继续获取表达式必须具有类类型