问题描述
我想写一个程序,以特定的方式获得用户的输入。
首先,我输入一个不包含空格的单词;
然后,我输入可能包含空格的另一个单词;
I am trying to write a program which gets user's input in a specific way.First, I input a word which contains no space;Then, I input another word which may contains space;And the program outputs the 2 words separately.
例如,我输入Tom a lazy boy
然后程序输出Tom:一个懒惰的男孩
For example, I input "Tom a lazy boy"Then the program outputs "Tom:a lazy boy"
这是我试图做的:
int main(){
string a;
cin >> a;
string b;
getline(cin, b);
cout << a << ":" << b<< endl;
}
我试过在cin后使用getline,但输出看起来像:一个懒惰的男孩
I tried using getline after cin, however the output looks like: "Tom: a lazy boy"
如果我输入汤姆(很多空间)一个懒惰的男孩,那么它会输出汤姆:(很多空间)一个懒惰的男孩
我想要不要那些空间。有没有更好的方法来做到这一点?
If I input "Tom(many spaces)a lazy boy" then it outputs "Tom:(many spaces)a lazy boy"and I want don't want those spaces. Is there a better way to do this?
我看到有些方法需要在cin后编辑字符串,但是我们能在输入阶段解决问题吗?
I see there are some ways which requires editing the string after cin, but can we solve the problem right at the input stage?
推荐答案
getline()
读取空格,如果您想忽略引领空格尝试:
getline()
reads whitespaces, if you want to ignore the leading whitespaces try:
cin.ignore();
getline(cin, b);
getline(cin, b);
string noLeadingWS = b.substr(b.find_first_not_of(' '),b.length()-b.find_first_not_of(' '));
cout << a << ": " << noLeadingWS<< std::endl;
这篇关于C ++函数getline后的Cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!