[英]C, counting the number of blankspaces
我正在编写一个将空格替换为' - '(< - this character)的函数。 我最终想要回复我做了多少改变。
#include <stdio.h>
int replace(char c[])
{
int i, cnt;
cnt = 0;
for (i = 0; c[i] != EOF; i++)
if (c[i]==' ' || c[i] == '\t' || c[i] == '\n')
{
c[i] = '-';
++cnt;
}
return cnt;
}
main()
{
char cat[] = "The cat sat";
int n = replace(cat);
printf("%d\n", n);
}
问题是,它正确地将字符串更改为“The-cat-sat”但是对于n,它返回值3,当它应该返回2.我做错了什么?
0
(零)值结束,而不是EOF
(所以:问题中的程序将扫描超出终端\\0
的字符串,直到它碰巧在某个地方找到-1
;但是你已经在UB的土地上,这里) size_t
,就像其他字符串函数一样) switch(){}
可以避免(IMO)丑陋的||
列表,添加案例也更容易。 unsigned replace(char *cp){
unsigned cnt;
for(cnt = 0; *cp ; cp++) {
switch (*cp){
case ' ' : case '\t': case '\n':
*cp = '-';
cnt++;
default:
break;
}
}
return cnt;
}
for循环结束条件中使用的EOF
是问题,因为您不使用的是检查文件/流的结尾。
for (i = 0; c[i] != EOF; i++)
EOF
本身不是一个字符,而是一个信号,表示流中没有可用的字符。
如果您要检查行结束,请使用
for (i = 0; c[i] != "\0"; i++)
#include <stdio.h>
int repl(int c);
int main(void){
int c, nc;
nc =0;
while ((c=getchar())!=EOF)
nc = replc(c);
printf("replaced: %d times\n", nc);
return 0;
}
int replc(int c){
int nc = 0;
for(; (c = getchar())!=EOF; ++c)
if (c == ' '){
putchar('-');
++nc;
} else putchar(c);
return nc;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.