Here is the code. I input 233
twice as the Variables g
and k
.
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int g, k;
cout << "type number :";
cin >> g;
cout << "your number : " << g << endl;
cout << "type another number: ";
cin >> k;
cout << "your number : " << k << endl;
int sum = g + k;
cout << "sum is :" << sum;
return 1;
}
why the terminal output type another number:
, then accept the input233
user passed in ,finally output the 5 spaces to the begging of the 4th line. Like this:
type number :233
your number : 233
type another number:233
your number : 233
sum is :466
instead of
the terminal output type another number:
, then accept the input 233
user passed in, finally output your number : 233
?
In my opinion, the terminal should be like this:
type number :233
your number : 233
type another number: 233
your number : 233
sum is :466
Please tell me why my expectation is wrong ,and introduce specifically why the C++ handles space in this way and any information or key mechanism about this.😄
Hey guys, I just finished my investigation about this little C++program on two platform.
My operating system: Windows10 Pro 22h2
Windows OS Builds: 19045.5247
My running platform: JetBrains Clion 2024.3.1 Pro
Clion toolchains:
Bundled MinGW Version 11.0 w64
Bundled CMake Version 3.30.5
Bundled GDB Version 15.2(all of them is Clion bundled)
Here is the keypoint: When I run this code in Visual Studio 2022(the newest version) on my PC, VS2022 terminal show the right expectaion like this:
type number :233
your number : 233
type another number: 233
your number : 233
sum is :466
Is that the error from MinGW?
But, when i change Clion toolchains from MinGW to Visual Studio, it still show show the wrong output in the terminal bundled by Clion:
type another number:233
your number : 233
Maybe this situation can be reproduced now.😄
2
Answers
I got the output of your expectation. Line number 13 of your code, also the extra spaces are sent directly to the terminal before waiting for the input. To achieve specific formatting, you must structure your code explicitly.
This works for me and controls when the buffered data will actually be flushed. There is no guarantee when the data will be flushed so calling
flush
explicitly will control it. Theendl
calls forcecout
to be flushed in addition to inserting a new line.