my programm needs to read integers (negatives and positives) from the user in a single string. After it reads all the integers, it should read eof and just display the numbers. Normally it is really easy to read integers, but if i want at the same time to check for eof i get that code. The problem is that with this code the variable a onlys read one character and it counts it as in ASCII code. For example if i type in 8 it will display 56.I know why it happens but that's the only way i can check for eof. And that's not the only problem since it won't read many or integers or many digits. Do i have to use strings or something like that?
1 2 3 4 5 6 7 8 9 10
int main ()
{
int a;
cin >> a;
while ( (a = getchar()) != EOF)
{
cout << a << endl;
cin >> a;
}
return 0;
#include "iostream"
using std::cin;
using std::cout;
int main()
{
int a;
while (cin >> a) {
cout << a << '\n';
}
if (!cin.eof()) {
cout << "Error in input stream\n";
}
}
Line 9 may need some explanation. The result of cin >> a is a reference to cin. While() expects a bool in the parenthesis, so the compiler looks for a way to convert cin to a bool. Fortunately there is such a conversion, it calls cin.good() So this is basically while (extracting an int is successful) ...