cin.getline()使用问题:输入回车无法触发无效输入判定
问题描述
编写C++代码实现获取用户输入的名字,需求为:当用户仅按下回车时判定为无效输入并提示重新输入,但当前代码中的空输入判定逻辑无法生效。尝试过cin.get、cin.ignore、cin.peek等方法,也将判定条件改为'\0'、0,均未解决问题。
原代码如下:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <iostream> using namespace std; struct customer { char fname[11]; }; void name(customer& name) { bool check = false; do { cout << "Enter your first name : "; cin.getline(name.fname, 10);// goal is to exit once press enter if (name.fname == '\n') //This doesnt work. i also tried using cin.get, cin.ignore, cin.peek and it still doesnt work, i tried changing the '\n' to '\0' and 0 just to see. { cout << "Invalid Entry\n"; } else check = true; } while (check != true); } int main() { customer cr; name(cr); return 0; }
问题排查与修复
核心问题分析
错误的空输入判定逻辑:
name.fname == '\n'是将字符数组的首地址与字符'\n'比较,两者类型不匹配(前者是char*,后者是char),永远不会相等,所以判定永远不触发。
当用户仅按下回车时,cin.getline会把目标字符数组的第一个元素设为'\0'(字符串结束符),以此表示读取到空字符串。补充优化点:
可以通过检查数组首元素是否为'\0',或用strlen函数判断字符串长度是否为0,两种方式都能正确识别空输入。
另外,cin.getline的第二个参数为10,意味着最多读取9个可见字符(留一个位置给'\0'),与fname[11]的数组大小兼容,无需调整。
修复后的代码
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstring> // 引入strlen函数所需头文件 using namespace std; struct customer { char fname[11]; }; void name(customer& cust) // 避免参数名与结构体名重名,改为cust { bool check = false; do { cout << "Enter your first name : "; cin.getline(cust.fname, 10); // 检查是否为空输入:两种方式选其一即可 if (cust.fname[0] == '\0') // 或者 if (strlen(cust.fname) == 0) { cout << "Invalid Entry\n"; } else check = true; } while (!check); } int main() { customer cr; name(cr); return 0; }
额外说明
- 修复了参数名与结构体变量名重名的混淆问题,将函数参数
name改为cust。 - 引入
<cstring>头文件以支持strlen函数(若选择用长度判断空输入)。 - 当用户输入空行时,
cin.getline会自动跳过换行符,无需额外调用cin.ignore处理缓冲区。
内容的提问来源于stack exchange,提问作者Rex Hunter
相关产品推荐
相关产品推荐

