C++ 在循环时执行 if 语句问题
C++ Do while loop with if statement issue
我有一个函数,可以让请求用户输入3个数据,输入数据后,系统会通过读取用户的输入来提示用户是否希望输入另一组输入,如果是'Y',系统将再次提示,如果是'N',那么函数就会结束。但是我有问题,如果用户输入"Y"或"N"以外的内容,系统应打印出错误消息并要求用户再次输入正确的选择。
我如何实现它,因为我试图在 do while 循环中输入 if 语句,但它无法正常工作。
void addstock()
{
char choice;
char result;
do
{
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
string itemid;
string itemdesc;
int unitprice;
int balstock;
string date;
//getting input from user
cout<<"";
getline(cin, itemid);
cout<<" Stock ID :";
getline(cin, itemid);
cout<<" Description :";
getline(cin, itemdesc);
cout<<" Price :";
unitprice = get_Integer();
date = dt;
cout<<itemid<<" "<<itemdesc<<" "<<unitprice<<" "<<balstock<<endl;
cout <<"Testing time is " <<date<<endl;
//storing to array
int i = getstockpilesize();
stockpile[i].itemid = itemid;
stockpile[i].itemdesc = itemdesc;
stockpile[i].unitprice = unitprice;
stockpile[i].date = date;
writeUserDatabase(); //update stockdatabasefile
cout<<" E[1;29mStock ID "<<itemid<<" added...E[0m"<<endl;
cout << "Do you want to key in another item (Y/N)" << endl;
cin >> choice;
result = toupper(choice);
cout << "1: " << result <<endl;
if (result !='Y' || result !='N')
{
cout << "Invalid choice, please enter again!" << endl;
cin >> choice;
choice = topper(choice);
}
}
while(result =='Y');
}
转动那个
if (result !='Y' || result !='N')
到
while (result !='Y' && result !='N')
只要result
既不是"Y"也不是"N",你的程序就会一直询问用户。
Y/N 答案处理应该是它自己的一个做。您的解决方案仅适用于一个错误的输入 - if{}
中的代码永远不会重复,即使输入重复错误也是如此。
因此,您需要确保重复输入及其处理,直到获得正确的输入:
do
{
cin >> choice;
result = toupper(choice);
cout << "1: " << result <<endl;
if (result !='Y' && result !='N')
{
cout << "Invalid choice, please enter again!" << endl;
}
}
while (result != 'Y' && result != 'N');
此外,你的 if() 语句是错误的,因为它永远是正确的。我也改变了。
在结束if (result !='Y' || result !='N')
if 条件之前,您应该说继续:
if (result !='Y' && result !='N') {
...
continue;//so it asks again user instead of checking condition for just 'Y'
}
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复