C++读取,从键盘,在时间直到用户的一个字符输入一个字母( 'A' .. 'Z' 或 '一个' .. 'Z')

问题描述:

为了回答这个问题:C++读取,从键盘,在时间直到用户的一个字符输入一个字母( 'A' .. 'Z' 或 '一个' .. 'Z')

读,直到用户输入一个字母('A','Z'或'a','z'),每次从键盘输入一个字符。

例如: LETTER? 4 //无效字符;所以,再问一个字母 LETTER? 。 //重复... LETTER?/// ... LETTER? # LETTER? k //最后,用户输入了一个字母!

我写了下面的代码:

#include <iostream> 
#include <stdio.h> 
#include <ctime> 
#include <string.h> 
#include <cstring> 
#include <ctype.h> 

using namespace std; 
int main(int letter){ 

    cout << "LETTER ? "; 
    cin >> letter; 
    if (!isalpha(letter)) 
    {main(letter);} 
    else 
    {}; 

     return(0); 

     }; 

如果它是一个数字是工作。 如果它是一个符号或一封信,它是在说信件?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ?信 ? (...)

你能帮我吗?

+0

你为什么要调用'main'递归?这是有点不确定的,如果我是对的,它在C++中是非标准的。使用循环代替。编辑:你的参数主要功能是不正确的。 –

+3

是的,这段代码无效。参见:[在C++中递归到main()是否合法?](http://*.com/questions/4518598/is-it-legal-to-recurse-into-main-in-c) – Blastfurnace

您当前的输入参数是int。 改为使用char或string。

int main(char letter) 
{ 
    cout << "LETTER ? "; 
    cin >> letter; 
    cin.clear();   //Good to have this (see comments below) 
    cin.ignore(200, '\n'); //This 2 lines will allow you to continue inputting when unexpected input is given 

    ...... 
} 

您的代码有未定义的行为。 C++标准不允许递归调用main函数。

同样在此声明的主要

int main(int letter){ 

不是C++标准兼容。如果编译器的文档将描述它,它可能是一个实现定义的main声明。

至于重复的邮件那么当你进入了一个非数字字符(字母变量int类型)的流std::cin了erraneous内部状态,如果你不会调用清除此状态

std::cin.clear(); 

性病:; cin不会允许输入其他内容。

如果不要求功能将是递归的,那么你可以写简单的

#include <iostream> 
#include <cctype> 

int main() 
{ 
    char letter; 

    do 
    { 
     std::cout << "LETTER ? "; 
     std::cin >> letter; 
    } while (std::cin && std::isalpha(letter)); 
} 

如果你唯一的任务是从键盘,直到读,Z,A,而不打印出进入ž字母,这应该工作:

#include <iostream> 

    using namespace std; 

    int main() 
    { 
    char letter = 'b'; 
    while (letter != 'a' && letter != 'A' && letter != 'Z' && letter != 'z') 
    cin >> letter; 
    return 0; 
    } 
+0

@Blastfurnace我也想知道谁赞成这个答案:)即使不考虑if语句的无效条件,程序也会像原始程序那样做。:)在Russhia中,通常表示“没有100美元但有100个朋友“:) :) –

+0

对不起,我修好了。 @VladfromMoscow – user3486543

+0

@ user3486543尽管如此,它不同于线程想要拥有的作者。 –