1

Can somebody please tell me why it won't print my full address? The final output is "Your name is Syd and you live at 2845." Why is it doing this? I clearly state within the cout to print the address string. (by the way, I actually type 2845 SE Taylor Street)

#include <iostream>
using namespace std;

int main()
{
    string address;
    cout << "Please enter your address." << endl;
    cin >> address;
    cout << "You live at " << address << "." << endl;
    return 0;
}
4

2 回答 2

4
cin >> address;

这读取一个单词,在第一个空白字符处停止。阅读整行:

std::getline(cin, address);
于 2013-10-18T14:36:08.180 回答
2

输入运算符读取空格分隔的值。因此,如果您的地址中有空格,那么它将只读取第一个“单词。

更糟糕的是,如果你输入你的全名,第一个输入会读取第一个名字,第二个输入会读取第二个名字。

尝试使用std::getline读取整行,但首先std::cin.ignore(numeric_limits<streamsize>::max(),'\n');要跳过最后一个输入的换行符(或std::getline用于两个输入)。

于 2013-10-18T14:35:55.500 回答