c - 如何修改此程序以计算非空格字符的数量?

标签 c char

对于我的作业,我需要修改以下程序。我无法使用 strings.h。

int main(void)
{
 int c, countSpaces = 0;

printf("Type sentence:\n");

do
{
  c = getchar();     
  if (c == ' ')
    countSpaces = countSpaces + 1;
}
while (c != '\n');     

printf("Sentence contains %d Spaces.\n", countSpaces);

return 0;
}

我尝试使用

if (c != EOF)
    countSpaces = countSpaces + 1;
}
while (c != '\n');     

printf("Sentence contains %d Spaces.\n", countSpaces - 1);

但这似乎是一种老套且不优雅的方法。 任何人都可以帮助和/或向我解释如何做得更好吗?

提前致谢

最佳答案

The code I posted counts the spaces in a sentence, I want to modify it to count all the characters in the input sentence. – fbN 21 secs ago

if 条件之外设置另一个计数器。

#include <stdio.h>

int main(void)
{
    int c;
    int countSpaces = 0;
    int countChars = 0;

    puts("Type sentence:");

    do {
        c = getchar();
        countChars += 1;
        if (c == ' ') {
            countSpaces += 1;
        }
    } while (c != '\n');     

    printf("Sentence contains %d spaces and %d characters.\n", countSpaces, countChars);

    return 0;
}

两个注释。 foo += 1foo = foo + 1 的简写,没有 foo++ 的优先复杂性。

Blockless ifwhile 正在玩火。最终你会不小心写下这个。

if( condition )
    do something
    whoops this is not in the condition but it sure looks like it is!

始终使用 block 形式。

<小时/>
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 12 characters.

请注意,这里显示的是 12,因为它包含换行符。这是因为它正在检查 c 在已经被计数之后是什么。您可以通过检查读取的 c 来解决此问题。这是一个相当正常的“读取并检查”C 循环习惯用法。

// Note, the parenthesis around `c = getchar()` are important.
while( (c = getchar()) != '\n' ) {
    countChars++;
    if (c == ' ') {
        countSpaces++;
    }
}
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 11 characters.

关于c - 如何修改此程序以计算非空格字符的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698165/

相关文章:

c - exec()函数如何维护内存空间?

c - 通过参数引用从程序返回 exec 输出

c - 在哪里记录 C 或 C++ 中的函数?

c - 交换/交换指针时的未定义行为

c - arr 和 *arr 有什么区别?

c++ - 示例程序崩溃

c++修改函数内部的char

c - 数组元素的类型不完整

c - 使用 C 将 char * 传递给 fopen

python - 可变长度前缀字符串的操作