【问题标题】:Counting the number of spaces in C program计算C程序中的空格数
【发布时间】:2018-10-16 10:15:54
【问题描述】:

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

#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();



}

【问题讨论】:

  • main() 是过时的。声明为int main(void)int main(int argc, char **argv)
  • 在调用任何scanf() 系列函数时:1) 始终检查返回值(而不是参数值)以确保操作成功。 2) 当使用输入/格式说明符时:'%s' 或 '%[...]' 总是包含一个比输入缓冲区长度小 1 的 MAX FIELD WIDTH 修饰符,因为这些项目总是附加一个 NUL 字节到输入。这也避免了缓冲区溢出和由此产生的未定义行为的任​​何可能性
  • 为了便于阅读和理解:1) 一致地缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前不缩进。建议每个缩进级别为 4 个空格 注意:将右大括号 '}}' 视为单独的语句。 2)遵循公理:每行只有一个语句,并且(最多)每个语句一个变量声明。 3)单独的代码块(forifelsewhiledo...while switchcasedefault)通过一个空行。

标签: c


【解决方案1】:

程序无法正确计算总字符数和空格数? 原因之一是语句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

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多