gpt4 book ai didi

c++ - 如何在C++中检查用户输入

转载 作者:行者123 更新时间:2023-12-01 19:30:10 27 4
gpt4 key购买 nike

在下面的代码中,我试图在类“SOMECLASS”的公共(public)空间中创建一个函数,该函数将接受由浮点值组成的用户输入(在私有(private) 同一类的空间)并验证用户输入。如果输入的值不是 float ,则会显示错误消息,并且用户将有机会重新输入该值。但是,一旦输入一些垃圾,循环就会从头开始运行,使用户再次输入所有这些值。

P.S:我知道可以创建多个循环来分别检查每个值,如果语句正确则中断循环,但我想知道是否有更简单的方法可以做到这一点。

提前感谢您的帮助。

void SOMECLASS::USER_INPUT() {
bool loopBool = true; // it is used to manage the do/while loop below;

do { // the loop is going to run for as long as the boolean is true;

cout << " Enter the frequency of the cumputer's CPU in GHz: ";
cin >> float1;

if (!float1) { // checks if the value entered is valid;
cin.clear();
cin.ignore (numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT!!!" << endl << endl;
}

else {
cout << " Enter the Hard Drive Capacity in TB: ";
cin >> float2;

if (!float2) { // checks if the value entered is valid;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT" << endl << endl;
}

else {
cout << " Enter the capacity of your RAM in GB: ";
cin >> float3;

if (!float3) { // checks if the value entered is valid;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "INVALID INPUT" << endl << endl;
}
loopBool = false;
}
}
} while (loopBool);
};

输出:

Computer #1/2
|--> Enter the frequency of the cumputer's CPU in GHz: 2.3
|--> Enter the Hard Drive Capacity in TB: 4
|--> Enter the capacity of your RAM in GB: asd
INVALID INPUT

`--> The final cost is: ...

期望的输出:

Computer #1/2
|--> Enter the frequency of the cumputer's CPU in GHz: 2.3
|--> Enter the Hard Drive Capacity in TB: 4
|--> Enter the capacity of your RAM in GB: asd
INVALID INPUT
|--> Enter the capacity of your RAM in GB: 16
`--> The final cost is: ...

最佳答案

如果数字必须为 float (小数),那么你可以这样做:-天花板(数字)<>楼层(数字)

如果它是整数值,则下限和上限将相等。

关于c++ - 如何在C++中检查用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158004/

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