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

Hi All. I'm attempting to output all lines from a text file that do not meet the criteria in the control structure -- i.e. no blank lines, no symbols, etc. However, when I run this code it outputs everything, not taking into consideration my specifc requirements. If anyone could tell me what I'm doing wrong it would be greatly appreciated.

Michael Edenfield
  • 28,070
  • 4
  • 86
  • 117

3 Answers3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

When you repeat the same action multiple times, that's a sign you need a function:

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

First of all you can test it separately, then your condition will be much simplier and less error prone:

if ( !beginsWith( temp,  "-----" )
      && !beginsWith( temp, "HEADER" )
      && !beginsWith( temp, "SUBID#" )
      && !beginsWith( temp, "REPORT" )
      && !beginsWith( temp, "DATE" )
      && temp != "" ) 
Slava
  • 43,454
  • 1
  • 47
  • 90
0

Short version (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;
utnapistim
  • 26,809
  • 3
  • 46
  • 82