Search code examples
c++inputcin

How to have all the inputs on the same line C++


I was asked to enter an hour and a minute on the same line. But when I enter the hour, it automatically goes to a new line, and I'm only able to enter the minute on the next line. However, I want to enter the hour and minute on the same line with a colon between them. It should look like this

Time: 4:54 

But my code produces this:

Time: 4 

54

cout << "\n\tTime: "; 
cin >> timeHours;
cin.get();
cin >> timeMinutes;

Solution

  • The behavior depends on the input provided by the user.

    Your code works as you want, if the user would enter everything (e.g.14:53) on the same line and press enter only at the end:

    Demo 1

    Now you can have a better control, if you read a string and then interpret its content, for example as here:

    string t; 
    cout << "\n\tTime: "; 
    cin >> t;
    stringstream sst(t);
    int timeHours, timeMinutes;
    char c; 
    sst>>timeHours>>c>>timeMinutes;
    

    Demo 2