如何避免阅读文本文件中的注释? [英] How to avoid reading comments in text file?

查看:97
本文介绍了如何避免阅读文本文件中的注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我已使用此代码成功将0到10之间的一些随机数写入我的文件(以下只是一些演示此问题的示例代码):

Currently I've successfully write to my file some random numbers between 0 to 10 with this code(below is just some sample code to demonstrate the problem):

for (int i = 1; i <= size; i++)
{
    type = rand () % 3;
    switch (type)
    {
    case 0:  afile << rand () % 10;
             break;
    case 1:  afile << rand () % 10;
             afile << "\t\t";
             afile << rand () % 10;
             break;
    case 2:  afile << rand () % 10;
             afile << "\t\t";
             afile << rand () % 10;
             afile << "\t\t";
             afile << rand () % 10;
             /*afile << "8";
             afile << "\t";
             afile << "7";
             afile << "\t";
             afile << "2";*/
    }

    afile << "\t\t" << "// Possible type " << i << endl;
}

然后在执行代码后,我的afile如下所示:

then my afile look like this after executing the code:

8       // Possible type 1
1       7       // Possible type 2
4       0       3       // Possible type 3

当我从该文件读取数据并输出到另一个文件时,会发生问题:

The problem occur when I read the data from this file and output to another file:

int type;

while (afile >> type)
{
    if(type == 0) 
    {
        afile >> .........;
        ..........
    } 
        else if(type == 1) {.........}
        else if(type == 2) {.........}
    }       
}
...................................... 

我的输出文件在第一行之后停止读取,因为它也读取了注释,该注释是要处理的无效数据,如果删除注释,则一切正常.那么我该如何克服这种情况呢?谢谢.

My output file stop reading after the first line since it's also read the comment which is invalid data to process, if I delete the comment then everything is working fine. So how can I overcome this situation? Thank you.

推荐答案

您有几个合理的选择:

  • 将整行读入std::string,扫描并删除任何注释,然后从剩下的任何地方创建一个std::istringstream并从中进行流处理以提取非注释值

  • read the entire line into a std::string, scan for and remove any comment, then create a std::istringstream from whatever's left and stream from that to extract the non-comment values

在读取值之前,请使用>> std::wsafile.peek()查看下一个字符是否为'/':如果是这样,请跳过直到到达换行符.

before reading values, use >> std::ws and afile.peek() to see if the next character is a '/': if so skip until you reach a newline.

前者是一种习惯于C ++的有用技术(在您要报告带有数据问题的行号时会有所帮助),看起来像这样:

The former is a useful technique to get used to in C++ (helps when you want to report line numbers with data issues), and looks like this:

if (std::ifstream in(filename))
{
    std::string line;
    while (getline(in, line))
    {
        std::string::size_type n = line.find("//");
        if (n != std::string::npos)
            line.erase(n);

        std::istringstream iss(line);

        int atype;
        while (iss >> atype)
            ...etc...
    }

这篇关于如何避免阅读文本文件中的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆