如何处理包含空格的cin用户输入?

问题描述 投票:0回答:1

我刚刚开始学习C ++,并且在程序中遇到了一个小错误:

#include <iostream>
using namespace std;

int main()  {
    string name;
    int number;
    cout << "Hello!\n";
    cout << "Please enter your name: " << flush;
    cin >> name;
    cout << "Please enter a whole number: " << flush;
    cin >> number;
    cout << "Thank you for your cooperation, " + name + ". We will be contacting you again soon in regards to your order of " << number << " puppies.\n";
}

第一次尝试输入多个单词(例如,No One)时,程序将输出以下内容:

请输入一个完整的数字:谢谢您的合作,不可以。关于您订购0只幼犬的问题,我们会尽快与您联系。

[我在其他地方读到,cin将所有空格都视为相同(因此,空格将被当作返回来对待),如何避免这个问题?

c++ whitespace cin
1个回答
0
投票

尝试使用getlinehttp://www.cplusplus.com/reference/string/string/getline/这有什么帮助吗?

© www.soinside.com 2019 - 2024. All rights reserved.