如何让所有输入都在同一行 C++
How to have all the inputs on the same line C++
我被要求在同一行输入一小时和一分钟。但是当我输入小时时,它会自动换行,我只能在下一行输入分钟。但是,我想在同一行中输入小时和分钟,并在它们之间加一个冒号。它应该看起来像这样
Time: 4:54
但是我的代码产生了这个:
Time: 4
54
cout << "\n\tTime: ";
cin >> timeHours;
cin.get();
cin >> timeMinutes;
您可以按照以下方式进行:
cin >> timeHours >> timeMinutes;
根据 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.
行为取决于用户提供的输入。
如果用户在同一行输入所有内容(例如14:53
)并仅在末尾按回车键,您的代码就可以正常工作:
现在你可以更好地控制,如果你读取一个字符串然后解释它的内容,例如这里:
string t;
cout << "\n\tTime: ";
cin >> t;
stringstream sst(t);
int timeHours, timeMinutes;
char c;
sst>>timeHours>>c>>timeMinutes;
#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;
}
应该是这样的
#include <iostream>
using namespace std;
int main()
{ int hour,minute;
cin>>hour>>minute;
cout<<"Time:"<<hour<<":"<<minute;
return 0;
}
我被要求在同一行输入一小时和一分钟。但是当我输入小时时,它会自动换行,我只能在下一行输入分钟。但是,我想在同一行中输入小时和分钟,并在它们之间加一个冒号。它应该看起来像这样
Time: 4:54
但是我的代码产生了这个:
Time: 4
54
cout << "\n\tTime: ";
cin >> timeHours;
cin.get();
cin >> timeMinutes;
您可以按照以下方式进行:
cin >> timeHours >> timeMinutes;
根据 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.
行为取决于用户提供的输入。
如果用户在同一行输入所有内容(例如14:53
)并仅在末尾按回车键,您的代码就可以正常工作:
现在你可以更好地控制,如果你读取一个字符串然后解释它的内容,例如这里:
string t;
cout << "\n\tTime: ";
cin >> t;
stringstream sst(t);
int timeHours, timeMinutes;
char c;
sst>>timeHours>>c>>timeMinutes;
#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;
}
应该是这样的
#include <iostream>
using namespace std;
int main()
{ int hour,minute;
cin>>hour>>minute;
cout<<"Time:"<<hour<<":"<<minute;
return 0;
}