如何使用包含空格的 cin 处理用户输入?
How does one process a user input with cin that contains whitespace?
我刚开始学习 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
)时,程序将输出以下内容:
Please enter a whole number: Thank you for your cooperation, No. We will be contacting you again soon in regards to your order of 0 puppies.
我在别处读到 cin
对所有白人 space 都一视同仁(所以 space 会和 return 一样对待),我怎么能避免这个问题?
尝试使用 getline http://www.cplusplus.com/reference/string/string/getline/
这有什么帮助吗?
#include <iostream>
#include <string>
int main() {
std::string name;
int number;
std::cout << "Hello!\n";
std::cout << "Please enter your name: " << std::flush;
getline(std::cin, name);
std::cout << "Please enter a whole number: " << std::flush;
std::cin >> number;
std::cout << "Thank you for your cooperation, " + name + ". We will be contacting
you again soon in regards to your order of " << number << " puppies.\n";
return 0;
}
我刚开始学习 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
)时,程序将输出以下内容:
Please enter a whole number: Thank you for your cooperation, No. We will be contacting you again soon in regards to your order of 0 puppies.
我在别处读到 cin
对所有白人 space 都一视同仁(所以 space 会和 return 一样对待),我怎么能避免这个问题?
尝试使用 getline http://www.cplusplus.com/reference/string/string/getline/ 这有什么帮助吗?
#include <iostream>
#include <string>
int main() {
std::string name;
int number;
std::cout << "Hello!\n";
std::cout << "Please enter your name: " << std::flush;
getline(std::cin, name);
std::cout << "Please enter a whole number: " << std::flush;
std::cin >> number;
std::cout << "Thank you for your cooperation, " + name + ". We will be contacting
you again soon in regards to your order of " << number << " puppies.\n";
return 0;
}