C++ 在循环时执行 if 语句问题

C++ Do while loop with if statement issue

本文关键字:if 语句 问题 执行 循环 C++      更新时间:2023-10-16

我有一个函数,可以让请求用户输入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'
 }