如何将所有输入都放在同一行C ++ [英] 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;
推荐答案
行为取决于用户提供的输入.
The behavior depends on the input provided by the user.
如果用户将在同一行中输入所有内容(例如 14:53
)并仅在最后按回车键,则您的代码将按您的要求工作:
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:
现在,如果您读取字符串然后解释其内容,则可以得到更好的控制,例如:
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;
这篇关于如何将所有输入都放在同一行C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!