gpt4 book ai didi

关于 getline(cin, string) 的 C++ 快速问题

转载 作者:行者123 更新时间:2023-11-28 03:39:00 25 4
gpt4 key购买 nike

自从我编写 C++ 代码以来已经有一段时间了,我忘记了收集字符串输入时发生的一件烦人的事情。基本上,如果这循环回来,比如说如果你使用负数,那么它会在第二轮跳过员工姓名行中的 cin。我记得之前遇到过这个问题,并且在输入字符串之前或之后必须清除或执行类似的操作。请帮忙!

PS 另外,为了获得额外帮助,任何人都可以在下面帮助我进行正确的循环。我如何检查字符串输入中的值以确保它们输入了值?

#include <string>
#include <iostream>
#include "employee.h"

using namespace std;

int main(){

string name;
int number;
int hiredate;

do{

cout << "Please enter employee name: ";
getline(cin, name);
cout << "Please enter employee number: ";
cin >> number;
cout << "Please enter hire date: ";
cin >> hiredate;

}while( number <= 0 && hiredate <= 0 && name != "");

cout << name << "\n";
cout << number << "\n";
cout << hiredate << "\n";

system("pause");
return 0;
}

最佳答案

您想将循环条件更改为是否未设置以下任何一项。只有当所有三个 都未设置时,逻辑 AND 才会触发。

do {
...
} while( number <= 0 || hiredate <= 0 || name == "");

接下来,使用 cin.ignore()按照@vidit 的规定,消除阅读换行符时出现的问题。

最后,也是重要的一点,如果输入一个字母字符作为整数而不是……整数,您的程序将运行一个无限循环。为了缓解这种情况,请使用 isdigit(ch)来自 <cctype>图书馆。

 cout << "Please enter employee number: ";
cin >> number;
if(!isdigit(number)) {
break; // Or handle this issue another way. This gets out of the loop entirely.
}
cin.ignore();

关于关于 getline(cin, string) 的 C++ 快速问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com