notClickBait
notClickBait

Reputation: 101

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;

Upvotes: 3

Views: 16545

Answers (4)

Avnish Nishad
Avnish Nishad

Reputation: 1852

it should be like this

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

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

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

}

Upvotes: 1

Tin Po Chan
Tin Po Chan

Reputation: 125

#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;
}

Upvotes: 1

Vtik
Vtik

Reputation: 3130

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.

Upvotes: 3

Christophe
Christophe

Reputation: 73366

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

Upvotes: 2

Related Questions