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

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

Hi,

I have tried this also:

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

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

try this: the compare function isn't needed.

string junk;
      string junk1 = "cls";
      while( inFile >> junk  && junk != junk1)
             ;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.