并行数组输入异常:第二次循环跳过员工姓名输入的解决方法
问题原因与解决方法
问题根源
你遇到的问题是输入缓冲区残留的换行符导致的:
- 第一次输入工时后,
cin >> hours[index]只会读取数字,输入时按下的回车键(换行符\n)会留在输入缓冲区里。 - 第二次循环调用
getline(cin, empName[index])时,会直接读取这个残留的换行符,误以为你输入了空姓名,因此跳过姓名输入步骤。
解决方法
有两种常用的修复方式:
方法一:清空输入缓冲区(支持带空格的姓名)
在读取工时后,用cin.ignore()跳过缓冲区里的换行符,确保下一次getline能正常读取输入。修改后的代码如下:
#include <string> #include <iostream> #include <limits> // 需要包含这个头文件使用numeric_limits using namespace std; const int SIZE = 5; int main() { string empName [SIZE]; int hours[SIZE]; int index = 0; for (index; index <= SIZE-1; index++) { cout << "Enter the Employee " << index +1 << " name: "; getline(cin,empName[index]); cout << "\nEnter the Employee hours: "; cin >> hours[index]; // 清空输入缓冲区中直到换行符的所有内容 cin.ignore(numeric_limits<streamsize>::max(), '\n'); } }
方法二:统一用cin读取姓名(仅支持无空格姓名)
如果员工姓名不含空格,可以直接用cin >> empName[index]替代getline,cin会自动跳过空白字符(包括换行符),代码修改如下:
#include <string> #include <iostream> using namespace std; const int SIZE = 5; int main() { string empName [SIZE]; int hours[SIZE]; int index = 0; for (index; index <= SIZE-1; index++) { cout << "Enter the Employee " << index +1 << " name: "; cin >> empName[index]; // 替换为cin读取 cout << "\nEnter the Employee hours: "; cin >> hours[index]; } }
这种方式更简单,但无法读取带空格的姓名(比如"Mary Smith")。
内容的提问来源于stack exchange,提问作者admiral general aladeen
相关产品推荐
相关产品推荐

