C ++使用if语句问题执行while循环

时间:2015-04-18 13:27:24

标签: c++

我有一个功能,可以让请求用户输入3个数据,输入数据后,系统会提示用户是否希望输入另一组输入,通过读取用户的输入,如果是& #39; 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');
  }

3 个答案:

答案 0 :(得分:1)

转过来

if (result !='Y' || result !='N')

while (result !='Y' && result !='N')

并且您的计划会一直询问用户,因为result既不是&#39; Y&#39;也不是&#39; N&#39;

答案 1 :(得分:0)

在结束if (result !='Y' || result !='N')条件之前,您应该继续说:

 if (result !='Y' && result !='N') {
      ...
      continue;//so it asks again user instead of checking condition for just 'Y'
 }

答案 2 :(得分:0)

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()语句是错误的,因为它总是如此。我也改变了。