C++ 如何在c++;
在下面的代码中,我试图在类“SOMECLASS”的公共空间中创建一个函数,该函数将接受由浮点值组成的用户输入(在同一类的私有空间中声明)并验证用户输入。如果输入的值不是浮点值,则会显示一条错误消息,用户将有机会重新输入该值。然而,一旦输入了一些垃圾,循环就从一开始就运行,使用户再次输入所有这些值 附言:我知道可以创建多个循环来分别检查每个值,如果语句正确,则中断循环,但我想知道是否有更简单的方法来做到这一点 谢谢你的帮助C++ 如何在c++;,c++,visual-c++,input,C++,Visual C++,Input,在下面的代码中,我试图在类“SOMECLASS”的公共空间中创建一个函数,该函数将接受由浮点值组成的用户输入(在同一类的私有空间中声明)并验证用户输入。如果输入的值不是浮点值,则会显示一条错误消息,用户将有机会重新输入该值。然而,一旦输入了一些垃圾,循环就从一开始就运行,使用户再次输入所有这些值 附言:我知道可以创建多个循环来分别检查每个值,如果语句正确,则中断循环,但我想知道是否有更简单的方法来做到这一点 谢谢你的帮助 void SOMECLASS::USER_INPUT() { bo
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
|--> Enter the capacity of your RAM in GB: 16
`--> The final cost is: ...
如果强制要求数字为浮点数(小数),那么您可以:- Ceil(编号)楼层(编号) 如果它是一个整数值,那么floor和ceil将相等。如果(!float1)如何从有效的
0.0
中识别失败的输入?您需要检查流的状态。
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: ...