-1

say I have a file which looks like this:

x 1
y 2 
z 3

what im trying to do is looping through the file and store it inside a variable called header, when ever the header is equal to "x", "y" or "z", i want to store the numbers after it inside a variable called value like this:

string header;
string value;
ifstream readFile("filename.txt");

while (!readFile.eof()) {
    readFile >> header;

    if (header == "x") {
        //store 1 to value
    }
    else if (header == "y") {
        //store 2 to value
    }
    else if (header == "z") {
        // store 3 to value
    }
}

can someone help me please as i cant figure out a way to achieve it

Barmar
  • 596,455
  • 48
  • 393
  • 495
lukey765
  • 3
  • 2
  • [why `while (!readfile.eof())` is wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Barmar Oct 21 '16 at 21:42

1 Answers1

0

Use readfile >> value to store the number into value.

You shouldn't use while (!readfile.eof()). Test the value of the stream after performing the read attempt.

while (readFile >> header) {

    if (header == "x") {
        readfile >> value;
    }
    else if (header == "y") {
        readfile >> value;
    }
    else if (header == "z") {
        readfile >> value;
    }
}

Since they're all doing the same thing, you don't need 3 different if statements, you can combine them.

while (readFile >> header) {

    if (header == "x" || header == "y" || header == "z") {
        readfile >> value;
    }
}
Barmar
  • 596,455
  • 48
  • 393
  • 495