从 cin 读取不会返回整个输入字符串
Reading from cin doesn't return entire input string
我必须提示用户使用两个单独的输入输入他们的名字和身高,一个用于英尺,一个用于英寸。然后我必须显示他们输入的内容。例如:姓名,您身高 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
.
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 用户输入字符串的文件附加问题..C++
- 从 cin 读取不会返回整个输入字符串
- 输出返回编号。等于输入字符串的单词的字符串数
- 控制台未正确读取输入字符串
- 使用终止程序的指针在数组中输入字符串
- 如何删除用户输入字符串末尾的空字符?
- 在循环中使用 cin.get() 输入字符串
- 如何从输入字符串中提取特定位置的字符?
- 用户输入字符串的结构的搜索向量
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何在 c++ 中读取输入字符串,忽略空格
- FSTREAM的问题读取确定,但不编写用户输入字符串
- boost::split会在输入字符串不是常量时更改输入字符串吗?
- 通过键盘输入字符串数组和 int 数组的数组大小
- Zlib 放气输入大于原始输入字符串的字符
- C 忽略输入字符串
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词