C函数输入字符串并计算

标签 c arrays string function

    #include <stdio.h>
    #include <string.h>
    #define SIZE 30
    int countWord(int a[]);
    int countSpace(int a[]);
    int countVowel(int a[]);
    int printResult(int a[]);

int main()//starting main 
{
    char string1[SIZE];
    printf("%s","Enter a string less than 29 characters");
    scanf("%29[^\n]",string1);  //anything except \n.

    printResult(string1);
}
int countWord(int a[]){
    int count=1;
    for(size_t i=0;i<SIZE&&a[i]!='\0';++i){ 
        if(a[i]==' '){
            count++;
        }
    }
    return count;
}
int countSpace(int a[]){
    int count1=0;
    for(size_t i=0;i<SIZE&&a[i]!='\0';++i){ 
        if(a[i]==' '){
            count1++;
        }
    }
    return count1;
}
int countVowel(int a[]){
    int count2=0;
     for(size_t i=0;i<SIZE&&a[i]!='\0';++i){
         if(strchr("aeiouAEIOU", a[i])){
            count2++;
        }
     }
     return count2;
}
int countNum(int a[]){
    int count3=countWord(a)-countVowel(a)-countSpace(a);
    return count3;
}
int printResult(int a[]){
    printf("Your sentence include\n");
    printf("Number of words:%d\n",countWord(a));
    printf("Number of spaces:%d\n",countSpace(a));
    printf("Number of vowels:%d\n",countVowel(a));
    printf("Number of consonants and special characters:%d\n",countNum(a));
}

这个程序是要求用户输入一个字符串并计算有多少个单词、空格、元音......但在输入字符串后我得到了非常错误的结果。我认为逻辑很好,并且正在努力寻找这里的任何问题

最佳答案

struggling to find any issues here

节省时间,启用所有警告。这是关键错误。

评论类型。

int printResult(int a[]);

  char string1[SIZE]; 
  printResult(string1);
<小时/>

"""abc def ""abcd" 字数统计错误。

替代方案:为单词的开头设置一个标志。

int countWord(int a[]){
int countWord(const int_but_I_suspect_you_want *a) {
  int count=0;
  int start_of_word_possible = 1;
  while (*a) {
    if (isspace(*a)) {
      start_of_word_possible = 1;
    } else {
      if (start_of_word) count++;
      start_of_word_possible = 0;
    }
    a++;
  }
  return count;
}

关于C函数输入字符串并计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974126/

相关文章:

c - 带有指针的预期标识符

javascript - 在 javascript 中使用二维数组并尝试从中读取值给出 "Uncaught TypeError: Cannot read property ' 0' of undefined"

arrays - 如何避免快速创建对象数组的副本

c# - 将json字符串转换为字符串数组

java - 正则表达式将字符串拆分为句子

python - 从字符串中提取坐标

c - 取消引用指针错误

c - fgets() 多次使用时会导致 C 程序崩溃

c - 解析字符串(Unix Shell)

c++ - 快速复制数组到数组