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

问题描述:

我对C++很陌生,但我知道Java。我得到了一项任务,其中程序要求输入“主动军事(是/否):”并根据输入做出决定。我试图通过验证输入来防止程序表单混淆。我目前正在使用意大利面代码,因为我无法弄清楚。请不要判断。我也不以此为荣。C++验证用户输入为字符或字符串

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循环吗?我真的想要简化这一点。正如我所说的,我并不为现在的状态感到自豪。

+0

您还在使用goto吗? – taocp 2014-10-02 18:09:24

+2

所以......你在Java中使用了'goto'?真的,同时有两种语言之间有许多差异,基本流程结构几乎相同(分支,循环等) – crashmstr 2014-10-02 18:10:55

+0

@crashmstr他说他知道Java的,不是说他知道编程。只知道一门语言只是冰山一角。 – 2014-10-02 18:31:50

我建议不要使用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

我建议使用'std :: toupper'或'std :: tolower',这样你就可以用一个if语句来处理大写和小写。 – 2014-10-02 18:43:51

  1. 尝试使用字符变量而不是字符串(因为你只使用字符)

以下代码会产生类似的效果

#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; 

} 
+1

如果用户输入“y”或“n”作为第一个提示,并且类似地选择“c”或“m”作为第二个提示,则代码将失败。请阅读'std :: toupper'和'std :: tolower'。 – 2014-10-02 18:45:31