#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int upper=0;
int digit=0;
int i=0;
char s[30];
char c;
printf("Enter sentence: ");
fgets(s, 30, stdin);
//s[strlen(s) - 1] = '\0';
while(c=getchar() && c!='\n')
{
c = s[i];
if(isupper(c))
{
upper++;
}
if(isdigit(c))
{
digit++;
}
i++;
}
printf("Number of upper case letters............... %d", upper);
printf("\n");
printf("Number of digits........................... %d", digit);
printf("\n");
printf("Program done. ");
return 0;
system("PAUSE");
}
如何在fgets()之后删除多个换行符? 我尝试在fgets()
之后实现以下行s [strlen(s) - 1] =&#39; \ 0&#39;;
但这不起作用,我的程序没有运行所有代码。
没有代码-----&gt; s [strlen(s) - 1] =&#39; \ 0&#39;;
这是输出:
Enter sentence: Whats UP 1234
Number of upper case letters............... 3
Number of digits........................... 4
Program done.
Process returned 0 (0x0) execution time : 9.340 s
Press any key to continue.
正如您所看到的,我的程序可以运行但是我必须按多次输入并且有很多换行符 然后在最后,程序运行最后一段代码。
该程序假设计算字符串中大写字母和数字的数量 进入。有人可以解释为什么会这样吗?
答案 0 :(得分:-1)
感谢Jongware:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int upper=0;
int digit=0;
int i=0;
char s[30];
char c;
printf("Enter sentence: ");
fgets(s, 30, stdin);
//correction: getchar() has been removed from the while condition.
while( c!='\n')
{
c = s[i];
if(isupper(c))
{
upper++;
}
if(isdigit(c))
{
digit++;
}
i++;
}
printf("Number of upper case letters............... %d", upper);
printf("\n");
printf("Number of digits........................... %d", digit);
printf("\n");
return 0;
system("PAUSE");
}