简体   繁体   English

它不会显示完整地址

[英]It won't print full address

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." 最终输出是“您的名字叫Syd,您的年龄为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) (顺便说一句,我实际上输入的是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;
}
cin >> address;

This reads a single word, stopping at the first white-space character. 这将读取一个单词,并停在第一个空格字符处。 To read a whole line: 要阅读整行:

std::getline(cin, address);

The input operator reads space separated values. 输入运算符读取以空格分隔的值。 So if your address have a space in it then it will read just the first "word. 因此,如果您的地址中有空格,那么它将仅读取第一个“单词”。

And worse, if you enter your full name, the first input will read the first name, and the second input will read the second name. 更糟糕的是,如果您输入全名,则第一个输入将读取名字,第二个输入将读取第二名字。

Try to use std::getline to read the whole line, but first do std::cin.ignore(numeric_limits<streamsize>::max(),'\\n'); 尝试使用std::getline读取整行,但首先执行std::cin.ignore(numeric_limits<streamsize>::max(),'\\n'); to skip the newline from the last input (or use std::getline for both inputs). 从最后一个输入中跳过换行符(或对两个输入都使用std::getline )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM