cin and buffer problem
Hi I have question regarding cin and buffer. I want to make a simple io progra开发者_如何学运维m which takes integers.
Anyway I stumbled to a problem with buffer. Using MinGW in windows7 the following code will print out all four integers that I input. But when I switch to SunOS and compile it with G++ it will only print out the first integer. Is this a compiler issue or is it a operating system issue?
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "Enter four integers: ";
cin >> i;
cout << "\nYou entered the numbers: " << i << " ";
cin >> i; cout << " ";
cin >> i; cout << " ";
cin >> i; cout << " ";
return 0;
}
The code should print out the first number on pretty any system.
cout << " ";
versus
cout << " " << i;
Therefore many guidelines state to do only one operation per line. The cin just optically clutters the reading. Actually you never output i
excepted the first time.
In these lines:
cin >> i; cout << " ";
cin >> i; cout << " ";
cin >> i; cout << " ";
...you're reading a number (if possible) but then just printing out a space, not the number you just read. If you really need to do this, I'd probably write a small function, and use it:
int get_input() {
int ret;
cin >> ret;
cout << ret;
return ret;
}
// ...
cout << "Enter four integers: ";
for (int i=0; i<4; i++)
get_input();
I can't say I'm particularly excited about that function, but under the circumstances, it's probably at least a little better than nothing (just not much better).
精彩评论