我一直在跟随K&R第二版的C编程书,但在3.7部分中,这是函数和我的代码部分的截图:
#include <stdio.h>
#include <string.h>
/* trim: removing the trailing blanks, tabs and newlines */
int trim(char s[]);
int main(){
char s[] = "hello,world \t\t\t\t\n\n\n\n";
printf("%s\n", s);
int length = trim(s);
printf("%d\n", length);
return 0;
}
int trim(char s[]){
int n;
for (n = strlen(s) -1 ; n >= 0 ; n--)
if (s[n] != ' ' && s[n] != '\n' && s[n] != '\t')
break;
s[n+1] = '\0';
return n;
}
以下是我运行它后得到的输出: 显然结果长度为11,即"hello,world",但程序输出为10,原因是s[n+1] = '\n',而不是s[++n]。我认为应该是s[++n],否则我会得到错误的输出==> 10,怎么处理?有人能看一下吗?