c++inputterminalbufferflush

how the output and input mechanism work on the terminal of C++ in this example


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)

Terminal: CLion built-in terminal

CMakeLists:

cmake_minimum_required(VERSION 3.30)
project(untitled)

set(CMAKE_CXX_STANDARD 23)

add_executable(untitled main.cpp)

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 the wrong output in the terminal bundled by CLion:

type another number:233
     your number : 233

Maybe this situation can be reproduced now.😄


Solution

  • Inspired by previous answers and my extensive research, This problem has already solved. Thanks to all contributors!😄 The problem is from the platform CLion i used. We can solve it by this two url: here and here