2013-02-01 66 views
0

我正在做一个程序,要求用户输入字符流并打印出大写和小写字母的数量。我想用一个函数来做到这一点,但遇到一些麻烦打印it..for进入即时得到0, 0 会感谢你的帮助,以了解每一个字符输入的IM,我做错了:打印大写/小写字母

#include <stdio.h> 
#include <ctype.h> 

int case_letters(int ch); 

int main(void) 

{ 
    int x; 
    printf("please enter a some characters, and ctrl + d to see result\n"); 

    case_letters(x); 

    return 0; 
} 

int case_letters(int ch) 

{ 
    int numOfUpper = 0; 
    int numOfLower = 0; 

    while ((ch = getchar()) != EOF) 
    { 
     if ((ch = isdigit(ch)) || ch == '\n') 
     { 
      printf("please enter a valid character\n"); 
      continue; 
     } 


     else if ((ch = isupper(ch))) 
     { 
      numOfUpper++; 
     } 

     else if ((ch = islower(ch))) 
     { 
      numOfLower++; 
     } 

    } 

    return printf("%d, %d", numOfUpper, numOfLower); 
} 

回答

3

所有您的if语句将不同的值分配给ch,并且不检查ch的值。

例如,如果你输入正确的char,这

if ((ch = isdigit(ch)) || ch == '\n') 

将分配给0ch,因为isdigit(ch)将返回0。我猜你需要

if (isdigit(ch) || ch == '\n') 

同为islowerisupper

+0

谢谢分配!现在得到它:)是我怎么称呼功能是好的,但?在主要@meh – MNY

+0

基本上,它很好。但是,我会删除参数,我会在函数中声明'ch',而不是在'main'中声明。然后在函数中再次打印消息,而不是在'main'中。换句话说,我会写这样的'main':'int main(void){case_letters();返回0; }'。 –

+0

感谢您的反馈!@meh – MNY

1
if ((ch = isdigit(ch)) || ch == '\n') 
      ^-- assignment, not equality test. 

你跟ISDIGIT()和isupper()和islower判断()的返回值捣毁的ch价值,使原有的用户输入的值,只要你做的破坏isdigit测试。

尝试

if (isdigit(ch) || ch == '\n') 
    else if (isupper(ch)) 
    else if (islower(ch)) 

代替。不需要保存任何值。

+0

谢谢@MarcB – MNY