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

13,188

Solution 1

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

Solution 2

You can do that as the following :

cin >> timeHours >> timeMinutes;

according to the documentation :

the user is expected to introduce two values, one for variable a, and another for variable b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a tab, or a new-line character.

Solution 3

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    string input;
    char symbol;
    int hour, min;
    cout << "Time: ";
    getline(cin, input);
    stringstream(input) >> hour >> symbol >> min;

    return 0;
}

Solution 4

it should be like this

#include <iostream>
using namespace std;
int main()

{ int hour,minute;
cin>>hour>>minute;

cout<<"Time:"<<hour<<":"<<minute;
return 0;

}
Share:
13,188
notClickBait
Author by

notClickBait

Updated on August 29, 2022

Comments

  • notClickBait
    notClickBait over 1 year

    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;