0

Hi,

I am getting a segmentation fault at the following line in the code. I am reading a file using ifstream. The file contains some initial junk data followed by useful data. I wish to read and discard the junk data from the file, before I read the useful data. When i read the following string "cls" i know that i have read all the junk data and now i will read the useful data.

I am using "compare" operator to compare the value read from the file and "cls". I am getting a segmentation fault at line number 4. Following is my code:

string junk;
      string junk1 = "cls";
      inFile >> junk;
      while(!(junk.compare(junk1)))
      {
               inFile >> junk;
      }

I am unable to figure the cause. any help is appreciated.

Thanks

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by Ancient Dragon
0

I don't see why it's a segfault, but you are using compare incorrectly. Remember that it returns 0 if the strings are equal, so you want to keep looping while it is not 0. You are doing the opposite, looping as long as the string IS "cls". You could just use != if you want.

do {
    inFile >> junk;
} while (junk != junk1);
0

Hi,

I have tried this also:

while((junk.compare(junk1)) != 0)
{
inFile >> junk;
}

Still getting a segmentation fault. Am i using compare correctly now?

Edited by happygeek: fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.