Why does std :: cin output whatever is given to it?

I am learning C ++ and obviously one of the first steps is learning input and output. However, I ran into a problem 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, since everything that was printed on one line, So the code is:

#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 should also be noted that when I entered 5 it sits directly next to that, as in "this5", although there should be space there. Then, as soon as I hit enter, it will print it out as it should look like, "this is 5".

I tried this without a space and it does the same thing, and I tried it with a new line 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 have searched the internet looking for why and I am on my way. I am using CLion with MinGW and CMake. My CMakeLists.txt file looks like this:

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 am doing wrong or what might be wrong with my setup?

+3


source to share





All Articles