3

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;
1

4 Answers 4

3

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.

2

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

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

it should be like this

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

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

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

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.