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

戏子无情 提交于 2021-02-09 09:01:08

问题


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:


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




回答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.




回答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;
}



回答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;

}


来源:https://stackoverflow.com/questions/37647249/how-to-have-all-the-inputs-on-the-same-line-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!