sodiumnitrate
sodiumnitrate

Reputation: 3143

Reading words from a file and printing if a certain word is encountered in C++

I have recently started tinkering with C++, and I'm trying to figure out how to read from a file. I have a file that begins with:

   1 !NTITLE
solvent mask generated by cctbx
      64       0      64      72       0      72      96       0      96
 3.91500E+01 4.46750E+01 6.10130E+01 7.26100E+01 7.17200E+01 7.53500E+01

(theres a blank line above the first line)

I am trying to read this word by word and printing the word mask as follows:

string myString;
ifstream xplorFile("mask.xplor");

if(!xplorFile){
    cout << "error opening file" <<endl;
    return -1;
}

while (!xplorFile.eof()) {
    getline(xplorFile, myString, ' ');
    if (myString == "mask") {
        cout << myString << endl;
    }
}

which outputs mask, as expected. However, if I try to print solvent instead by changing the if statement to

if (myString == "solvent") {
        cout << myString << endl;
}

I get no output. Similarly, if I try !NTITLE I get no output. Why isn't the comparison not working?

Upvotes: 1

Views: 48

Answers (2)

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

change

while (!xplorFile.eof()) {
    getline(xplorFile, myString, ' ');

to

while (xplorFile >> mystring) {

My guess is that since solvent is at the beginning of the line not preceded by a space, then the getline function with delimiter ' ' produces !NTITLE\nsolvent. Using the >> operator will resolve that because it tokenizes on all whitespace.

Upvotes: 1

MORTAL
MORTAL

Reputation: 383

easy way to get file contents word by word is like this

while (xplorFile >> myString) {
    if (myString == "mask") {
        cout << myString << endl;
    }
}

Upvotes: 1

Related Questions