Reputation: 459
sorry for the noob question, but I'm new to C++.
I need to read some information, line-by-line, from a file, and perform some calculations, and output into another file. For example, we read a unique ID for each line, a name, and 2 numbers. The last 2 numbers are multiplied, and in the output file, the ID, name and product are printed line by line:
input.txt:
2431 John Doe 2000 5
9856 Jane Doe 1800 2
4029 Jack Siu 3000 10
output.txt:
ID Name Total
2431 John Doe 10000
9856 Jane Doe 3600
4029 Jack Siu 30000
My code is similar to this, but only the first line appears in the output file. If I press Enter
repeatedly, the other lines appear in the output file:
#include <fstream>
using namespace std;
ifstream cin("input.txt");
ofstream cout("output.txt");
int main () {
int ID, I, J;
string First, Last;
char c;
cout << "ID\tName\t\Total\n";
while ((c = getchar()) != EOF) {
cin >> ID >> First >> Last >> I >> J;
cout << ID << " " << First << " " << Last << " " I * J << "\n";
}
return 0;
}
That's my only problem, that the values don't appear in the output file, unless I press Enter
repeatedly, then close the program. Can anyone suggest a fix for my code above, to have it do the task without keyboard input? Thanks!
Upvotes: 2
Views: 323
Reputation: 2295
While I was looking for the answer I though I better check and make sure it worked. I got some build errors and got a little carried away from there.
Hope this helps!
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream indata("input.txt");
if(!indata)
{ // file couldn't be opened
cerr << "Error: input.txt could not be opened" << endl;
exit(1);
}
ofstream output("output.txt");
if(!output)
{ // file couldn't be opened
cerr << "Error: output.txt could not be opened" << endl;
exit(1);
}
int ID, I, J;
char First[10], Last[10];
output << "ID\tName\tTotal\n";
while (!indata.eof())
{
indata >> ID >> First >> Last >> I >> J;
output << ID << " " << First << " " << Last << " " << I * J << endl;
}
indata.close();
output.close();
return 0;
}
Upvotes: 0
Reputation: 1186
This is because you used getchar() in your while loop condition. Not sure what you were trying to do, but getchar() reads a char from stdin. What you should have done, is check if cin failed or encountered EOF.
Upvotes: 1
Reputation: 40849
using namespace std;
ifstream cin("input.txt");
ofstream cout("output.txt");
You've hidden the real std::cin and std::cout...and will later read from them.
while ((c = getchar()) != EOF) {
But here you use the real std::cin to check for EOF.
Upvotes: 7
Reputation: 7772
The getchar()
call reads waits for you to type a character (and press Enter) since it reads from stdin (standard input). Try changing the loop condition to stop reading when cin
reaches end of file.
EDIT
You should also use different names for input and output streams -- there are already cin
and cout
in the std
namespace.
Upvotes: 6