2016-08-14 145 views
-4

我的代码出现了一些问题,它出现在我编译并运行代码后它会输出两次,也是错误的输出。C++循环和scanf验证字母表,大写字母和数字

我的任务是重复输入数字/字母/大写并相应输出结果。至于while循环,我相信我必须把while(1)

#include <stdio.h> 
int main() 
{ 
    char c; 
    int num; 

    printf("\nEnter a character: "); 
    scanf("%c", &c); 

    if ((c >= 'a' && c <= 'z')) 
     printf("%c\nIt is an alphabet.", c); 

    if ((c >= 'A' && c <= 'Z')) 
     printf("%c\n It is a capital alphabet.", c); 

    if (c <= '1' ||c >= '1') 
     printf("\nIt is a numeric"); 

    else 
     printf("error"); 

return 0; 
} 
+0

应该有一个'else if'链......它不在那里...... – LogicStuff

+1

'if(c <= '1' ||c > ='1')'是错的。 - 您是否尝试*调试代码? –

+1

请确定你确切地知道你正在学习什么语言。你的代码类似于C. C和C++是非常不同的语言。 –

回答

0

需要三个改变。

首先使用else if

其次测试数字使用c >= '0' && c <= '9'

,最后但并非最不重要:使用getchar()作为循环的最后声明吃\n字符是在缓冲区,而不是采取scanf

+0

雅吧。 @LogicStuff。在此之前使用ASCII值出现在我的脑海中。 –

1

你需要这样的工作:

#include <stdio.h> 

int main() 
{ 
char c; 
int num, int general=0; 

printf("\nEnter a character: "); 
scanf("%c", &c); 



if ((c >= 'a' && c <= 'z')) { 
    printf("%c\nIt is an alphabet.", c); 
    general++; 
    } 


if ((c >= 'A' && c <= 'Z')){ 
    printf("%c\n It is a capital alphabet.", c); 
    general++; 
    } 

if (c <= '1' ||c >= '1') { 
    printf("\nIt is a numeric"); 
    general++; 
    } 


if (general==0) 
    printf("error"); 

return 0; 
} 

或者您可以在“捕捉和切换”中使用。