nev*_*int 1 c++ iteration file-processing
我有以下数据,例如:
34 foo
34 bar
34 qux
62 foo1
62 qux
78 qux
这些是基于第一列排序的.
我想要做的是处理以34开头的行,但我还希望文件迭代在找不到34s之后退出,而不必扫描整个文件.我该怎么做?
原因是因为要处理的行数非常大(~10 ^ 7).那些以34开头的人只占其中的1-10%左右.
我知道我可以grep这些行并将其输出到另一个文件中,但这太繁琐了,并且会产生更多的磁盘空间消耗.
此代码说明了使用"continue"失败的尝试:
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main () {
string line;
ifstream myfile ("mydata.txt");
vector<vector<string> > dataTable;
if (myfile.is_open())
{
while (! myfile.eof() )
{
stringstream ss(line);
int FirstCol;
string SecondCol;
if (FirstCol != 34) {
continue;
}
// This will skip those other than 34
// but will still iterate through all the file
// until the end.
// Some processing to FirstCol and SecondCol
ss >> FirstCol >> SecondCol;
cout << FirstCol << "\t << SecondCol << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用break而不是continue!continue返回到循环的头部,只跳过当前的迭代,同时break保持循环良好.
在一个不相关的注释,你的代码有一个错误导致它挂起如果由于任何原因无法读取文件(例如,当程序试图访问它时用户删除它,用户删除文件所在的USB记忆棒,等等.).这是因为循环条件如:
while (!file.eof())
Run Code Online (Sandbox Code Playgroud)
很危险!如果文件流进入错误状态,eof则永远不会true,并且循环将继续打开... 您需要测试文件是否处于任何可读状态.这可以通过使用隐式转换为布尔值来完成:
while (file)
Run Code Online (Sandbox Code Playgroud)
只要文件未完成读取且没有错误,这将导致循环运行.