对于我的作业,我需要修改以下程序。我无法使用 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 += 1
是 foo = foo + 1
的简写,没有 foo++
的优先复杂性。
Blockless if
或 while
正在玩火。最终你会不小心写下这个。
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/