【问题标题】:How do I Read file line by line and ignore comments?如何逐行读取文件并忽略注释?
【发布时间】:2020-01-14 14:40:02
【问题描述】:

我有一个文本文件包含

//range of X
X=1-5

//range of Y
Y=1-5

如何读取文件以使其忽略 cmets 和空行并获取以下输出:

X=1-5

Y=1-5

int main(){

    string fileName,X;
    cout << "Please enter filename: " ;
    cin >> fileName;


    ifstream infile;    
    infile.open(fileName);  

        if (!infile){       
            cerr << "Error opening : " << fileName << ", file does not exist" << endl;
            return -1;      
        }


    while(getline(infile, X)){
        cout << X;
    }

    infile.close();
    return 0;
}

【问题讨论】:

  • 您是否使用了假设?即,仅单行 cmets?评论总是在开头在线?我看到您开始输入代码来读取文件,但您也应该输入您尝试解决这部分问题的代码。
  • 如果是X=1-5 // Here is a comment呢?
  • 是的,我只有以 // 开头的单行 cmets

标签: c++ file sorting readfile getline


【解决方案1】:

根据您的问题,cmets 总是使用运算符“//”在不同的行上。

if(X.size() == 0 || (X.size() >= 2 && X[0] == '/' && X[1] == '/')){
     continue;
}

【讨论】:

    【解决方案2】:

    替换

    while(getline(infile, X)){
        cout << X;
    }
    

    由

    while(getline(infile, X)){
        if((X.size() >=2 && X.substr(0,2) != "//") && X.find_first_not_of(' ') == X.npos) cout << X;
    }
    

    用于存储两行的编辑:

    将您的 while 替换为以下内容

    vector<string> twoStrings;
    while(getline(infile, X)){
    if((X.size() >=2 && X.substr(0,2) != "//") && X.find_first_not_of(' ') == X.npos)
        {
            cout << X;
            twoStrings.push_back(X);
        }
    }
    //Now the first line is stored in twoStrings[0] and the second line is stored in twoStrings[1]
    

    【讨论】:

    • 如果该行是/apples 或[spaces] X=5 怎么办……您的代码将无法正常工作。
    • 我修复了一些小错误。我不知道它是否真的有效,但现在看起来还不错。
    • @anonymous 你的if 仍然有问题,你所有的条件都是错误的。它应该更像这样:if ((X.substr(0,2) != "//") &amp;&amp; (X.find_first_not_of(' ') != X.npos))
    • i cout 并得到 x=1-5 y=1-5,但是如何将 2 个字符串存储在 2 个不同的变量中?
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2015-12-22
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2022-01-04
    • 2012-10-29
    • 2014-11-30
    相关资源
    最近更新 更多