Why is std::cin outputting whatever is given to it?

176 Views Asked by At

I've been working on learning C++, and obviously one of the first steps is learning to get input and output. However, I've encountered an issue where, when I call std::cin and use it to put the returned information into a variable, it then prints out whatever was given to it, AS WELL as whatever was printed out on the same line. So the code:

#include <iostream>

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    cout << "Hello World" << endl;
    cout << "Testing this ";
    int x;
    cin >> x;
    cout << x;
    return 0;
}

returns:

C:\Users\...\LearnCpp.exe
Hello World
Testing this5
Testing this 5
5
Process finished with exit code 0

It's also noteworthy that when I entered 5, it is directly next to this, as in "this5", even though there should be a space there. Then, once I hit enter, it prints it out as it should look, "this 5".

I've tried it without the space and it does the same, and I've tried it with a newline after "Testing this ", and it prints 5 twice:

C:\Users\...\LearnCpp.exe
Hello World
Testing this
5
5
5
Process finished with exit code 0

I've scoured the internet looking for why, and I'm at my wits end. I'm using CLion with MinGW and CMake. My CMakeLists.txt file looks like:

cmake_minimum_required (VERSION 3.2)
project (LearnCpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)
add_executable(LearnCpp ${SOURCE_FILES})

Can anyone see what I'm doing wrong, or what might be wrong with my setup?

0

There are 0 best solutions below