C ++验证用户输入为字符串或字符串

时间:2014-10-02 18:08:56

标签: c++ loops

我是C ++的新手,但我了解Java。我得到了一个任务,程序要求输入“Active Military(Y / N):”并根据输入做出决定。我试图通过验证输入来防止程序形式混淆。我目前正在使用意大利面条代码,因为我无法弄明白。请不要判断。我也不为此感到骄傲。

lable1:
cout << "Active Military (Y/N): ";
cin  >> strMilitary;

//Check for valid input
if(strMilitary == "Y")
{
    goto lable2;
}
if(strCounty == "N")
{
    goto lable2;
}

cout << "Invalid Input" << endl;
goto lable1;

//Continue
lable2:

lable3:
cout << "Mecklenburg or Cabarrus (C/M): ";
cin  >> strCounty;

//Check for valid input
if(strCounty == "C")
{
    goto lable4;
}
if(strCounty == "M")
{
    goto lable4;
}

cout << "Invalid Input" << endl;
goto lable3;

//Continue
lable4:

有什么方法可以使用while循环吗?我真的想简化这个。正如我所说,我对其现状并不感到自豪。

2 个答案:

答案 0 :(得分:2)

我建议不要使用goto语句。

以下是如何使用while循环获取军队的输入:

#include <iostream>

using namespace std;

int main()  
{   
  char military = '\0'; // any initial value that's not Y or N
  while(military != 'Y' && military != 'N') {
    cout << "Active Military (Y/N): ";
    cin >> military;
  }

  cout << "You have entered: " << military << endl;

  return 0;
}

答案 1 :(得分:2)

  1. 尝试使用char变量而不是字符串(因为您只使用字符)
  2. 以下代码会产生类似的效果

    #include<iostream>
    using namespace std;
    
    int main()
    {
      char military = '\0', county = '\0';
    
      while(1)
      {
        cout << "Active Military (Y/N): ";
        cin  >> military; 
        if( military == 'Y' || military == 'N' ) 
        {
          // maybe call a method to do something, depending on the input         
          break; 
        }
        cout << "Invalid Input!!";
      }     
    
      while(1)
      {
        cout << "Mecklenburg or Cabarrus (C/M): ";
        cin  >> county; 
        if( military == 'M' || military == 'C' ) 
        {
          // call a method to do something, depending on the input         
          break; 
        }
        cout << "Invalid Input!!";
      }      
    
     return 0;
    
    }