Bob Shannon
Bob Shannon

Reputation: 648

Reading lines from a file -- removing extra spaces

I am using ifstream to get lines from a file and store them to a string. Each line contains a single word with no spaces.

    virtual void readFromFile(char* input){
        ifstream inf(input);

        if(!inf){
            cerr << "The specified file could not be found." << endl;
        }

        while(inf){
            string str;
            getline(inf, str);
            pushFront(str); // store it in my data structure

        }

        inf.close();
    }

file.txt

a <= returns length 1 (correct)
at <= returns length 3
ate <= returns length 4
rate <= returns length 5
irate <= returns length 6

When I call length() on the string corresponding to the very first of the file, it returns the correct value. However, calling length on strings corresponding all other lines results in a offset of +1. For example, if the length of the string is actually 5, it returns 6. Does this have something to do with new lines? If so, how can I properly extract these words from the file?

Upvotes: 0

Views: 758

Answers (2)

cpp-progger
cpp-progger

Reputation: 406

If the format in Your text file is defined, that every line contains exactly one word, so it is more easy and more sure to read this words.

void readFromFile(char* input){
    ifstream inf(input);
    if(!inf){
        cerr << "The specified file could not be found." << endl;
    }
    for( string word; inf >> word; )
        pushFront( word ); // store it in my data structure
}   // inf.close() is done automaticly leaving the scope

Upvotes: 0

Boris Strandjev
Boris Strandjev

Reputation: 46943

You are using vi as text editor so you can show the invisible characters by doing :set list. This will help you figure out what might be these additional characters you see on most of the lines.

In linux the usual line ending is "\r\n", which are in fact two characters. I am not exactly sure whether the getline will omit them both or not. However, just as a precaution you can add the following logic:

getline(inf, str);
int len = str.size();
if (str[len - 1] == '\r') {
   str.pop_back(); // not C++11 you do it str = str.erase(str.end() - 1);
}
pushFront(str); // store it in my data structure

Upvotes: 1

Related Questions