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;   
}

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

4

3 回答 3

1

If you look at a reference such as this you will see that the second argument to substr is the number of character not the ending position.

This means that e.g. temp.substr(0,5) might return "HEADE" which is indeed not equal to "HEADER". This means that all non-empty string will be output.

Also note that right now, you don't actually read lines but words as you separate the input on space.

于 2013-03-01T15:09:18.980 回答
0

短版(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;
于 2013-03-01T16:19:23.580 回答
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 != "" ) 
于 2013-03-01T15:26:19.010 回答