Hey guys, i am working with a program to basically read an input for a file and then storing it into a vector. my text file is called Sample.txt and contains data like this..

How are you coping with programming?  
The quick brown fox jumps over me.

Here are my codes..

int main (){
  
     vector<string>myVec; // declaring a vector

     int threshold ;
     cout << "Enter threshold number: " ;
     cin >> threshold;  //store user input into interger variable
     int i = 0;
   fstream readFile("sample2.txt"); // prepare to read from file
       string Numeral ;
    char delimeter = ' ';
    string word ;
while (getline(readFile,Numeral, delimeter))
{
    word = Numeral;
    i ++;
    
myVec.push_back(word);

}
    int g = myVec.size();

    for(int i = 0; i < g ; i ++){
        cout << myVec[i] << endl;
    }
    cout << i << endl;
    cout << g << endl;
    
}

Well, the output i am trying to achieve is basically listing down each word in the text file like this..

Expected Output
How
are
you
coping
with
programming? 
The
quick
brown
fox
jumps
over
me.

But for some reason, my output keeps coming out like this.

Current Output
How
are
you
coping
with
programming?

The
quick
brown
fox
jumps
over
me.

There is a gap before "The". I guess it is being caused due to "The" being in a new line. Is there any way i am able modify my codes to read each word in my text without worrying bout newlines and all?

Before you push_back the word, I think you can just test if it is a new line like this:

if(word == "\n")
  continue;

Let me know if that does what you're looking for.

Thanks,

Dave

if (line != "\n"){
myVec.push_back(line);
 //   }
}

did you mean something like this? i placed this in line 17 but the same output still comes out.

What you did will do exactly what my "continue" did, it is like a double-negative :)

However, it isn't working for me either - I guess this is not how you are supposed to check for newlines? Someone else will fix my mistake soon :)

I am not sure if the mistake is just a newline itself or what. For some reason, i feel that the word "The" in the second line is attached with a " " which is why its coming out like that.

NathanOliver - it doesn't seem to like comparing a string to a character - could you have meant word!="\0" ? When I did that, it still did not skip the blank line.

Dave

Yes sorry I did mean word!="\0" . In this case the call to getline leaves the string blank if there is a newline so this will work to get rid of the extra line.

if (!word.empty())
    myVec.push_back(word);

However when I was doing this and I copied your text file there was a couple extra spaces after the ? in the first sentence that was causing a problem. After I deleted those extra spaces it worked perfectly. If your program has to deal with cases like that then a different approach will be needed.

This article has been dead for over six months. Start a new discussion instead.