【发布时间】:2012-11-10 21:50:06
【问题描述】:
我无法弄清楚我的简单 IO 问题是什么:
这是我执行 IO 的代码:
cout << "Enter an Employee name: ";
getline(cin, empName);
cout << "Employee Position: " ;
cin >> empPos;
cout << "Enter the Number of Years of Experience: ";
cin >> numOfExp;
cout << "Enter the deprtment Number: ";
cin >> deptNum;
这是我的错误输出: 第一次读取名称时一切正常,但第二次看起来像是自动传递到名称中,而不要求用户输入任何名称。
这是我的输出:
Name: Unknown
Department Number: 0
Employee Position: E
Years of Experience: 0
Salary: 0
Total Number of Employees: 1
Enter an Employee name: arasd d
Employee Position: s
Enter the Number of Years of Experience: 12
Enter the deprtment Number: 12
Name: arasd d
Department Number: 12
Employee Position: s
Years of Experience: 12
Salary: 0
Total Number of Employees: 1
Enter an Employee name: Employee Position:
如您所见,最后一行是问题所在; 知道如何解决这个问题吗?
【问题讨论】:
-
getline在停止读取时表现不同。 -
不要混用
getline和>>。此外,您完全忘记检查任何输入操作的返回值。这基本上是一场灾难。 -
此时我不做任何错误检查,我只是想确保程序在假设用户输入正确输入的情况下运行。
-
至于混合getline和>>,我不知道如何读取输入之间有空格的字符串并将其存储到单个字符串变量中。