从 cin 读取不会返回整个输入字符串

Reading from cin doesn't return entire input string

本文关键字:输入 字符串 返回 cin 读取      更新时间:2023-10-16

我必须提示用户使用两个单独的输入输入他们的名字和身高,一个用于英尺,一个用于英寸。然后我必须显示他们输入的内容。例如:姓名,您身高 x 英尺 y 英寸。我编写的程序运行,但它没有按预期工作。在我为第一个问题(即名称(编写输入后,程序会跳过其他问题并结束程序。

#include <iostream>
#include <string>
using namespace std;
int main ()
{
int name;
int f;
int i; 
// Start: Enter Name
cout << "What is your name?" << endl;
cin >> name; 
// Enter height 
cout << "How many feet tall are you tall?" << endl;
cin >> f;
// Enter inches
cout << "How many inches tall are you after feet?" << endl;
cin >> i;
// End: All info entered
cout << name << " you are " << (f) << " feet " << (i) << " inches tall." << endl;
system("pause");
return 0;
}

首先,也是最重要的,您应该将name的类型从int更改为string。您当前的程序尝试将您的输入读取为数字而不是文本name

现在,如果您的程序仍然无法按预期工作,请确保在键入输入时name您尝试输入的名称之间没有空格(空格、制表符等(。例如,John的输入会很好,但John Smith不会。这是因为>>运算符与cin值一起使用时,所有空格都相同。这意味着按空格键与按程序的回车键相同。如果您尝试输入全名,请考虑使用getline读取输入,直到按下回车键。

获取线示例:

cout << "What is your name?";
getline (std::cin,name);

总结: 将int name;更改为string name;。如果您需要阅读多个单词的名称,请使用getline.