如何在C-string为空时输出错误提示?附程序运行异常咨询
解决你的C-string输入验证和菜单显示问题
Hey Sara, let's work through your two main issues step by step:
1. 处理空C-string的输入验证
当用户直接按回车输入空内容时,cin.getline()会把C-string的第一个字符设为'\0'(空终止符)。你可以在inputPika函数里添加检查逻辑,判断输入是否为空,如果是空的就提示错误并要求重新输入。
修改后的inputPika函数如下:
void inputPika(char a[]) { const int SIZE = 40; bool isValid = false; while (!isValid) { cin.getline(a, SIZE); // 检查是否为空:第一个字符就是终止符 if (a[0] == '\0') { cout << "Error: Name cannot be empty! Please re-enter: "; } else { isValid = true; } } }
这样用户输入空内容时,会一直循环直到输入有效的非空字符串。
2. 解决菜单需要按回车才显示的问题
看你的main函数开头有一行cin.ignore();,这就是问题所在!程序刚启动时,输入缓冲区是空的,cin.ignore()会等待用户输入一个字符(回车)才会继续执行后面的代码,所以菜单要等你按回车才显示。
只需要删掉这行多余的cin.ignore();就可以了。另外,cin >> pick之后的cin.ignore()是必要的,因为cin >>会把输入的换行符留在缓冲区里,不忽略的话,下一次cin.getline()会直接读取这个换行符,导致输入为空。
修改后的main函数:
int main() { int pick = 0; const int SIZE = 40; char name[SIZE]; // 删掉这里的cin.ignore(); while (true) { display_menu(); cin >> pick; cin.ignore(); // 这个保留,用来清除换行符 switch (pick) { case 1: cout << "1. Input Name: "; inputPika(name); break; case 2: cout << "2. Display Name: "; displayPika(name); break; default: // 可以加个默认处理,防止用户输入无效选项 cout << "Invalid option! Please enter 1 or 2." << endl; break; } } }
完整修改后的代码
把所有修改整合起来,完整代码如下:
#include "stdafx.h" #include <stdio.h> #include <iostream> #include <cstring> using namespace std; void inputPika(char[]); void display_menu(); void displayPika(char[]); void display_menu() { //Display menu for user selection cout << "The Name game: " << endl; cout << "1. Pika Name " << endl; cout << "2. Display Pika Name " << endl; } void inputPika(char a[]) { const int SIZE = 40; bool isValid = false; while (!isValid) { cin.getline(a, SIZE); if (a[0] == '\0') { cout << "Error: Name cannot be empty! Please re-enter: "; } else { isValid = true; } } } void displayPika(char a[]) { cout << a << endl; } int main() { int pick = 0; const int SIZE = 40; char name[SIZE]; while (true) { display_menu(); cin >> pick; cin.ignore(); switch (pick) { case 1: cout << "1. Input Name: "; inputPika(name); break; case 2: cout << "2. Display Name: "; displayPika(name); break; default: cout << "Invalid option! Please choose 1 or 2." << endl; break; } } }
这样修改后:
- 输入空内容时会弹出错误提示,直到输入有效姓名
- 程序启动后会直接显示菜单,不需要先按回车
- 还加了默认选项处理,防止用户输入无效数字
内容的提问来源于stack exchange,提问作者Sara Kim
相关产品推荐
相关产品推荐

