写一个函数,从控制台逐行读取并打印每行的字符数,读取的行的最大长度应该是20个字符。
我有一些只是通过循环和打印一遍又一遍的输入字符串.我有问题 – 打印每个用户输入后的字符数,并设置最大字符输入为20的考试。谁能帮帮我?
char str[str_size];
int alp, digit, splch, i;
alp = digit = splch = i = 0;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
do {
printf("Input the string : ");
fgets(str, sizeof str, stdin);
} while (str[i] != '\0');
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else
{
splch++;
}
i++;
printf("Number of Alphabets in the string is : %d\n", alp + digit + splch);
}
解决方案:
我不明白你做什么用 do while
循环。所以我只是为你的情况提出另一个循环。我不确定,但希望这个代码是你想要的。
int main() {
char str[22];
int alp, digit, splch, i;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
printf("Input the string : ");
while (fgets(str, sizeof str, stdin)){
alp = digit = splch = 0;
for (i = 0; i < strlen(str); i++ ) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else if(str[i] != '\n')
{
splch++;
}
}
printf("alp = %d, digit = %d, splch = %d\n", alp, digit, splch);
printf("Input the string : ");
}
return 0;
}
OT,为了确定α或数字,你可以使用 isdigit()
和 isalpha()
函数。比你代码里用的东西简单多了。