如何在 C++ 中跳过读取文件中的一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/576677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I skip reading a line in a file in C++?
提问by neversaint
The file contains the following data:
该文件包含以下数据:
#10000000 AAA 22.145 21.676 21.588
10 TTT 22.145 21.676 21.588
1 ACC 22.145 21.676 21.588
I tried to skip lines starting with "#" using the following code:
我尝试使用以下代码跳过以“#”开头的行:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
int main() {
while( getline("myfile.txt", qlline)) {
stringstream sq(qlline);
int tableEntry;
sq >> tableEntry;
if (tableEntry.find("#") != tableEntry.npos) {
continue;
}
int data = tableEntry;
}
}
But for some reason it gives this error:
但由于某种原因,它给出了这个错误:
Mycode.cc:13: error: request for member 'find' in 'tableEntry', which is of non-class type 'int'
Mycode.cc:13: 错误:在“tableEntry”中请求成员“find”,这是非类类型“int”
回答by CTT
Is this more like what you want?
这更像你想要的吗?
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
fstream fin("myfile.txt");
string line;
while(getline(fin, line))
{
//the following line trims white space from the beginning of the string
line.erase(line.begin(), find_if(line.begin(), line.end(), not1(ptr_fun<int, int>(isspace))));
if(line[0] == '#') continue;
int data;
stringstream(line) >> data;
cout << "Data: " << data << endl;
}
return 0;
}
回答by sth
You try to extract an integer from the line, and then try to find a "#" in the integer. This doesn't make sense, and the compiler complains that there is no find
method for integers.
您尝试从该行中提取一个整数,然后尝试在该整数中找到一个“#”。这没有意义,编译器抱怨没有find
整数方法。
You probably should check the "#" directly on the read line at the beginning of the loop.
Besides that you need to declare qlline
and actually open the file somewhere and not just pass a string with it's name to getline
. Basically like this:
您可能应该在循环开始时直接在读取行上检查“#”。除此之外,您需要qlline
在某处声明并实际打开文件,而不仅仅是将带有其名称的字符串传递给getline
. 基本上是这样的:
ifstream myfile("myfile.txt");
string qlline;
while (getline(myfile, qlline)) {
if (qlline.find("#") == 0) {
continue;
}
...
}