Cin>>阅读输入

时间:2015-02-23 23:52:53

标签: c++ xcode

当我输入" M12 9UB"这段代码:

std::string postal_code;

cout << "Enter postal code: ";
cin >> postal_code;
cout << "Your postal code is: " << postal_code << endl;

输出为&#34;您的邮政编码为:M12&#34;。

那么如何让cin读取整行?

2 个答案:

答案 0 :(得分:2)

使用std::getline从流中读取整行:

std::getline(std::cin, postal_code);

Live example.

答案 1 :(得分:0)

您可以像这样使用C ++ getline函数:

#include <iostream>
using namespace std;

int main()
{
    std::string postal_code;

    cout << "Enter postal code: ";
    getline(cin,postal_code);
    cout << "Your postal code is: " << postal_code << endl;
}