gpt4 book ai didi

计算C程序中的空格数

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:46 26 4
gpt4 key购买 nike

小写和大写字母、特殊字符和数字都可以正常工作。该程序无法正确计算总字符数和空格数。我应该添加什么才能使这项工作?感谢您的帮助!

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

main(){
char cMessage[100];
int cChar,cLow=0, cUp=0, cSpec=0, cSpace=0, cNum=0;

printf("Enter your message: ");
scanf("%s", cMessage);

int x=0;
while(x<strlen(cMessage)){

printf("%c",cMessage[x]);
cChar++;

if(islower(cMessage[x])){ cLow++;}

else if(isupper(cMessage[x])){ cUp++;}

else if(cMessage[x] == ' '){ cSpace++; }

else if(isdigit(cMessage[x])){ cNum++; }

else{ cSpec++;
}
x++;
}
printf("\nTotal Characters: %d", cChar);
printf("\nTotal Lowercase Letters: %d", cLow);
printf("\nTotal Uppercase Letters: %d", cUp);
printf("\nTotal Special Characters: %d", cSpec);
printf("\nTotal Spaces: %d", cSpace);
printf("\nTotal Numbers: %d", cNum);
getch();



}

最佳答案

程序无法正确计算字符和空格总数?原因之一是语句 scanf("%s", cMessage); 不会读取空格或只读到空格。如果您想读取带空格的 cMessage,请使用 fgets()

fgets(cMessage,sizeof(cMessage),stdin);/* use fgets() instead of scanf() */

或者你可以像这样使用scanf()

scanf("%[^\n]", cMessage);/* it read the whitespaces also */

在这里阅读 fgets() 的手册页 https://linux.die.net/man/3/fgets

关于计算C程序中的空格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50200107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com