0

Okay, so I have a program that reads in a .txt file.

Here is the sample contents of the .txt file:

1 load grades.csv
2 save grades.csv
3 show all

I have it read in as a string command. In line 1 am able to read the command load in just fine(the command reads the grades.csv file), same goes for the save command. But for the next line I am not sure how to read the show all command as one word.

This is what I have as code:

if (command == load)
   {
    in.ignore();
    cout << "load" << endl;
   }
else if (command == "show all")  //this is the error, it only reads in **save**
    cout << "show" << endl;
else
    cout << "save" << endl;

This is running in the while loop. I feel like I have to use the ignore() function but I am not sure how I can implement that in the if-else statement.

Thanks

BaneGane
  • 1
  • 2
  • Possible duplicate of [Reading a full line of input](https://stackoverflow.com/questions/5882872/reading-a-full-line-of-input) – McLemore Nov 13 '17 at 01:16
  • What code are you using to read in the file? `cin` will only read until a space, so to read a full line you need to use `getline` – JGrindal Nov 13 '17 at 01:17
  • Okay, how would I implement the getline command? – BaneGane Nov 13 '17 at 01:19
  • 1
    `std::getline()` reads an entire line until EOL or EOF is reached. Use `std::istringstream` to parse individual words from each line that is read. – Remy Lebeau Nov 13 '17 at 01:42

2 Answers2

1

If you always have two words on each line, you can read those separately:

while (file >> command >> option)
{
    if (command == "load")
        cout << "load " << option << endl;
    else if (command == "show" && option == "all")
        cout << "show all" << endl;
    else if (command == "save")
        cout << "save " << option << endl;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

Instead of using cin, which only retrieves until the space, use:

while( std::getline( cin, s ) ) 
{
   // s will be a full line from your file.  You may need to parse/manipulate it to meet your needs
}
JGrindal
  • 793
  • 2
  • 8
  • 23
  • I use a while(!in.fail) loop. I can not change that because it will mess with the program. Do you know if it is possible to use it specifically with if-statements. – BaneGane Nov 13 '17 at 01:35