首页 文章

过滤getline收到的输入[关闭]

提问于
浏览
0
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;

int main() {

string firstFile, secondFile, temp;

ifstream inFile;
ofstream outFile;

cout << "Enter the name of the input file" << endl;
cin >> firstFile;

cout << "Enter the name of the output file" << endl;
cin >> secondFile;

inFile.open(firstFile.c_str());
outFile.open(secondFile.c_str());

while(inFile.good()) {  

    getline(inFile, temp, ' ');

        if (   temp.substr(0,4) != "-----"
            && temp.substr(0,5) != "HEADER" 
            && temp.substr(0,5) != "SUBID#"
            && temp.substr(0,5) != "REPORT"
            && temp.substr(0,3) != "DATE"
            && temp             != ""
            && temp             != "") 
        {
            outFile << temp;
        }
}

inFile.close();
outFile.close();

return 0;   
}

大家好 . 我试图输出不符合控制结构标准的文本文件中的所有行 - 即没有空行,没有符号等 . 但是,当我运行此代码时,它会输出所有内容,而不考虑我的具体要求 . 如果有人能告诉我我做错了什么,我将不胜感激 .

3 回答

  • 0

    如果查看引用such as this,您将看到 substr 的第二个参数是字符数而不是结束位置 .

    这意味着,例如 temp.substr(0,5) 可能会返回 "HEADE" ,这确实不等于 "HEADER" . 这意味着将输出所有非空字符串 .

    另请注意,现在,当您在空间上分隔输入时,实际上并不是读取行而是单词 .

  • 0

    当你多次重复同一个动作时,这就是你需要一个功能的标志:

    bool beginsWith( const std::string &test, const std::string &pattern )
    {
       if( test.length() < pattern.length() ) return false;
       return test.substr( 0, pattern.length() ) == pattern;
    }
    

    首先,您可以单独测试它,然后您的条件将更加简单并且不易出错:

    if ( !beginsWith( temp,  "-----" )
          && !beginsWith( temp, "HEADER" )
          && !beginsWith( temp, "SUBID#" )
          && !beginsWith( temp, "REPORT" )
          && !beginsWith( temp, "DATE" )
          && temp != "" )
    
  • 1

    简短版(C 11):

    const std::vector<std::string>> filter {
        {"-----"}, {"HEADER"}, ... }; // all accepted line patterns here
    
    while(getline(inFile, temp)) {
        for(const auto& s: filter)
            if (s.size() == temp.size() &&
                std::equal(s.begin(), s.end(), temp.begin()))
    
                outFile << temp;
    

相关问题