所以我正在尝试从文件中读入。如果一行中间或任何地方有一个“#”,我想忽略该行的其余部分,继续阅读。这是我的:
while(getline(pgmFile, temp))
{
istringstream readIn(temp);
lines++;
while(readIn >> convert)
{
//cout << temp[counter] << endl;
if (temp.length() == 0 || temp[counter] == '#' || temp[counter] == '\r' || temp[counter] == '\n')
{}
else
{/*cout << temp << endl;*/}
if(temp.at(counter) == '\n' || temp.at(counter) == '\r')
{}
if(convert < 57 || convert > 40)
{
pixels.push_back(convert);
}
}
对于这个输入文件:
P5
4 2
64
0 0 0 0 # don't read these: 1 1 1 1
0 0 0 0
它应该在 0 中读取,但在 # 之后没有任何内容。
temp是string类型,逐行读取。
非常感谢任何帮助!!!
最佳答案
在构建 istringstream
时,您可以在第一个 '#'
(如果存在)处剪切字符串。这将使您假装 '#'
永远不存在,从而简化其余逻辑:
while(getline(pgmFile, temp))
{
size_t pos = temp.find('#');
istringstream readIn(pos == string::npos ? temp : temp.substr(0, pos));
lines++;
...
}
由于您是逐行阅读,并且由于分隔符被丢弃,您也可以安全地跳过对 '\n'
字符的检查:它不会在那里。
关于c++ - 忽略 '#'之后的一切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19038192/