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