[英]C program add individual digits, lower and uppercase letters, and other characters
我试图让我的程序打印这些:
输出应该是存储在 (10+26+26+1=) 63 个计数器中的值 问题是:计算各种英文字母(小写和大写)的数量。 还要计算字符总数。
我的教授并没有像我的助教那样真正有帮助,因为他们从未真正涉足过这个问题; 他们只是假设我们一开始就知道 C 并且在电子邮件中没有反应。 对所有其他人感到抱歉,因为我是这个网站的新手并试图学习。 谢谢你的耐心。
#include<stdio.h>
#define MAXLINE 1000
main()
{
char str [MAXLINE];
int ndigit, nlower, nupper, nother;
int c;
printf("Enter any text with numbers or other characters if you like: ");
fgets(str,MAXLINE,stdin);
ndigit = nlower = nupper = nother = 0;
while ((c = getchar()) != EOF)
{
if (c >= '0' && c <= '9')
++ndigit;
else if (c >= 'a' && c <= 'a')
++nlower;
else if (c >= 'A' && c <= 'A')
++nupper;
else
++nother;
}
printf("Digits : %d Lowercase Letters %d Uppercase Letters %d Other characters %d\n", ndigit, nlower, nupper, nother);
}
}
我试过运行你的程序,你的程序有两个错误。
无论您在输入中输入什么字符串,所有内容都将存储在str
因为fgets(str,MAXLINE,stdin)
因此代码执行只会在您按下Enter或EOF后移至下一行和getchar()
。请参阅此问题fgets 有什么作用? fgets
是如何工作的。现在因为 getchar 永远不会处理您的整个输入,而循环变得无用。
以上是主要问题,删除fgets()
将允许getchar()
接受字符并且循环将起作用。另一个问题是else if (c >= 'a' && c <= 'a')
和 line else if (c >= 'A' && c <= 'A')
,你错误地代替z
和Z
使它们a
和A
,所以它不起作用。
更正这两个你的代码会很好。
这是你的程序。
#include<stdio.h>
#define MAXLINE 1000
main()
{
char str [MAXLINE];
int ndigit, nlower, nupper, nother;
char c;
printf("Enter any text with numbers or other characters if you like: ");
fgets(str,MAXLINE,stdin); //What Really Happens is whatever you are
//inputting is getting stored into the char array str
//Only after you press enter or EOF then
// execution move forward to getchar().
//So you type the whole string and then it all get stored in str and then
//comes no output because getchar never executes.
ndigit = nlower = nupper = nother = 0;
while ((c = getchar()) != '\n')
{
if (c >= '0' && c <= '9')
++ndigit;
else if (c >= 'a' && c <= 'a') //Change To (c>='a' && c<='z')
++nlower;
else if (c >= 'A' && c <= 'A') //Change To (c>='A' && c<='Z')
++nupper;
else
++nother;
}
printf("Digits : %d Lowercase Letters %d Uppercase Letters %d Other characters %d\n", ndigit, nlower, nupper, nother);
}
更改您的代码后成为。
#include<stdio.h>
#define MAXLINE 1000 //Redundant Line As You Are No Longer Using fgets.
int main() //Changed to int main()
{
char str [MAXLINE]; //Redundant Line As You Are No Longer Using fgets.
int ndigit, nlower, nupper, nother;
char c;
printf("Enter any text with numbers or other characters if you like: ");
ndigit = nlower = nupper = nother = 0;
while ((c = getchar()) != '\n')
{
if (c >= '0' && c <= '9')
++ndigit;
else if (c >= 'a' && c <= 'z')
++nlower;
else if (c >= 'A' && c <= 'Z')
++nupper;
else
++nother;
}
printf("Digits : %d Lowercase Letters %d Uppercase Letters %d Other characters %d\n", ndigit, nlower, nupper, nother);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.