0

I have the code below that reads lines of input from a file that are formatted as such: operation string [optional argument].

I pipe the contents of the file to the program by cat file.txt | ./program.

However, the code seems to process the last line of the file twice. Any idea why that might be happening?

Here is the code:

#include <iostream>
int main() {
    char operation, creditable;
    string owner;
    double money;
    int line=0;

    while (std::cin) {
        line++;
        std::cin >> operation;
        try {
            switch (operation) {
                case 'a':
                    std::cin >> owner >> creditable;
                    // code to deal with variables
                    break;
                case 'b':
                    std::cin >> owner >> money;
                    // code to deal with variables
                    break;
                case 'c':
                    std::cin >> owner;
                    // code to deal with variables
                    break;
                default:
                    throw std::runtime_error("invalid operation");
                    break;
            }
        }
        catch (std::runtime_error e) {
            std::cerr << "error on line " << line << ": " << e.what() << endl;
        }
    }
    return 0;
}

The file being processed (file.txt) looks like this:

a Alice y
a Jack n
a Bob y
b Alice +200.00
b Bob -50.0
Alex
  • 49
  • 8
  • 2
    Maybe you should process the entire line as string and use `while(std::getline(std::cin, tempstr))` instead. – Ron Oct 08 '17 at 19:01
  • 2
    Your loop `while (std::cin)` is really no different than `while (!std::cin.eof())`, and that condition is [always wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Some programmer dude Oct 08 '17 at 19:03
  • Oh, I see. `getline` into a `stringstream` should work, I will try that. – Alex Oct 08 '17 at 19:11
  • Just for education's sake: http://coliru.stacked-crooked.com/a/639545ab2426112d - free code review – sehe Oct 08 '17 at 19:17

0 Answers0