如何在do/while循环中验证不同类型的多输入(字符串与整数)?
解决C++输入验证问题:同时校验字符串与整数合法性
原代码仅能检测年龄的非数字输入错误,但无法校验姓名、家乡等字符串是否仅包含字母——只要年龄输入合法,哪怕字符串是纯数字也会被直接通过,不符合输入合规要求(字符串需为字母,整数需为数字)。
原代码
#include <iostream> #include <limits> #include <string> using namespace std; string firstName, secondName, homeTown; int age; int main() { do { cout << "Please enter your full name, hometown and age (e.g. John Doe London 25).\n\n"; cin >> firstName >> secondName >> homeTown >> age; if (cin.fail()) { cout << "\nInvalid input!\n\n"; cin.clear(); cin.ignore(); } else { break; } } while (1); cout << "\nYour Name is: " << firstName << " " << secondName << "\n" << "Your Hometown is: " << homeTown << "\n" << "Your Age is: " << age << "\n"; return 0; }
解决方案
核心思路
- 编写辅助函数判断字符串是否仅包含字母
- 在输入读取后,同时验证:输入流状态正常、年龄是合法整数、所有字符串仅含字母,全部满足才通过验证
修改后的完整代码
#include <iostream> #include <limits> #include <string> #include <cctype> // 用于isalpha函数 using namespace std; string firstName, secondName, homeTown; int age; // 检查字符串是否全为字母(支持大小写) bool isAllLetters(const string& str) { for (unsigned char c : str) { if (!isalpha(c)) { return false; } } return !str.empty(); // 同时确保字符串不为空 } int main() { bool isValid = false; do { cout << "Please enter your full name, hometown and age (e.g. John Doe London 25).\n\n"; cin >> firstName >> secondName >> homeTown >> age; isValid = true; if (cin.fail()) { isValid = false; } else { // 检查所有字符串是否仅含字母 if (!isAllLetters(firstName) || !isAllLetters(secondName) || !isAllLetters(homeTown)) { isValid = false; } } if (!isValid) { cout << "\nInvalid input!\n\n"; cin.clear(); // 清除错误状态 // 忽略缓冲区剩余的所有字符,直到换行,避免残留输入影响下一次读取 cin.ignore(numeric_limits<streamsize>::max(), '\n'); } } while (!isValid); cout << "\nYour Name is: " << firstName << " " << secondName << "\n" << "Your Hometown is: " << homeTown << "\n" << "Your Age is: " << age << "\n"; return 0; }
关键部分解释
辅助函数
isAllLetters:- 遍历字符串每个字符,用
isalpha判断是否为字母,将字符转为unsigned char避免isalpha处理负数值的未定义行为 - 同时检查字符串不为空,防止输入空串
- 遍历字符串每个字符,用
输入验证逻辑:
- 先检查
cin.fail()判断年龄是否为合法整数 - 若输入流正常,再逐一校验三个字符串是否符合全字母要求
- 任何一项不满足,标记输入无效,清理输入流的错误状态并忽略剩余输入,避免残留内容干扰下一次读取
- 先检查
循环控制:使用
isValid变量控制循环,仅当所有验证条件通过时退出循环
测试案例
正确输入示例
输入:
John Doe London 25
输出:
Please enter your full name, hometown and age (e.g. John Doe London 25). John Doe London 25 Your Name is: John Doe Your Hometown is: London Your Age is: 25
字符串含数字的错误输入示例
输入:
1 1 1 1
输出:
Please enter your full name, hometown and age (e.g. John Doe London 25). 1 1 1 1 Invalid input! Please enter your full name, hometown and age (e.g. John Doe London 25).
年龄输入非数字的错误输入示例
输入:
John Doe London a
输出:
Please enter your full name, hometown and age (e.g. John Doe London 25). John Doe London a Invalid input! Please enter your full name, hometown and age (e.g. John Doe London 25).
内容的提问来源于stack exchange,提问作者Ren
相关产品推荐
相关产品推荐

