c++ - 忽略 '#'之后的一切

标签 c++ skip chars

所以我正在尝试从文件中读入。如果一行中间或任何地方有一个“#”,我想忽略该行的其余部分,继续阅读。这是我的:

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/

相关文章:

c++ - 如何在 C++ 中创建用于编目随机变量的循环?

c++ - C++ 中 std::vector 的基本问题

c++ - 将 int 转换为 Char* 给出 ascii 值 C++

C语言-char[]输出中的 "Weird"个字符

c++ - 在 cuda __device__ 函数中分配 (malloc) double**

c++ - 与 Minecraft bukkit 服务器握手 - 发送服务器主机字段失败

Python:创建一系列有序数字,跳过第 N 个到第 N+D 个数字的倒数

java - 如何忽略 Buffered Reader 中 ' ' 之后的行的其余部分,或行上的特定字符?

c++ - 计算c++文件中的代码行数,跳过仅包含注释或空行的行

java - Java中如何处理unicode字符