0

Fairly simply question. Below is my code and I'm trying to read the first word for each line on a text file. I am pretty much new to C++ and basically illiterate, so a vivid explanation would be really helpful. Thanks in advance!

The output I want is:

Warrior (5 times), Status, Battle (5 times), Status (separate lines of course)

But what I get is:

Warrior (4 times), Status, Battle (5 times), Status

Here is my code:

int main() {
    string readText;
    string command;
    string firstName;
    string skip;
    int strength;
    ifstream inFile("warriors.txt");
    if (!inFile) {
        cout << "File will not open" << endl;
    }
    else {
        while (inFile >> readText) {
            getline(inFile, command);
            inFile >> command;
            if (command == "Warrior") {
                cout << "warrior" << endl;
            }
            else if (command == "Battle") {
                cout << "battle" << endl;
            }
            else if (command == "Status") {
                cout << "status" << endl;
            }
        }
    }
}

Another question on the side, why is it that when I change:

    while(inFile >> readText)

to

    while(inFile)

My output is now: Warrior (4 times), Status, Battle(5 times), Status, Status

Yourchingoo
  • 3
  • 1
  • 4
  • Your if conditions inside the while loop are very interesting ! How about cout << command << endl; – HazemGomaa Oct 02 '16 at 04:08
  • Change while (inFile >> readText) to while (inFile >> command) and remove getline(inFile, command); inFile >> command; – HazemGomaa Oct 02 '16 at 04:17
  • oh ... well that worked... thanks ! lol – Yourchingoo Oct 02 '16 at 04:22
  • Now, I haven't seen your data file, but one of the upsides and downsides of stuff like `inFile >> readText` is it stops when it finds whitespace. Upside is it makes parsing really easy if it's all you need and use. Downside is it leaves the whitespace in the stream for the next thing that comes along and if that whitespace is an end of line and the next thing that comes along is `std::getline`, `std::getline` consumes the end of line and returns... pretty much nothing. Avoid mixing them. – user4581301 Oct 02 '16 at 04:22

1 Answers1

0

you are reading multiple lines in one loop by using both (inFile >>) and getline(). Your while loop should look like

while (inFile >> command){
  cout << command << endl;  
}
HazemGomaa
  • 1,620
  • 2
  • 14
  • 21