题目:输入一个字符串,长度小于128,求字符串最后一个单词的长度,单词以空格隔开。
实例:
输入 hello world
输出 5
AC代码:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[200];
int n, word_n;
//fgets(str, 200, stdin);
//n = strlen(str)-1;
gets_s(str);//VS 2015只支持gets_s函数
n = strlen(str);
//fscanf(stdin,"%s",str);
//n = strlen(str);
printf("n %d\n",n);
while (n>0 && str[n - 1] == ' ')
n--;
word_n = 0;
while (n>0 && str[n - 1] != ' ') {
n--;
word_n++;
}
printf("%d\n", word_n);
getchar();
return 0;
}
很简单对不对!重点不是这个,请看fgets那两行代码。fgets是不是比gets函数安全,不会越界对吧。可是你可以试试贴到HWOJ上跑跑,心都碎了。为什么fgets就不对呢?说好的会添加换行符到str内的,我减去换行符了啊?我真心的以为是其他的问题,调了一下午,问了好多人,然并卵==
—————————- 分割线 ————————————–
我突然想到万一不会又换行符呢?下面的代码结果就AC了
int main() {
char str[200];
int n, word_n;
fgets(str, 200, stdin);
n = strlen(str);//尼玛啊,没有减1啊
//printf("n %d\n",n);
while (n>0 && str[n - 1] == ' ')
n--;
word_n = 0;
while (n>0 && str[n - 1] != ' ') {
n--;
word_n++;
}
printf("%d\n", word_n);
//getchar();
return 0;
}
至今凌乱中,如有高人看到,万望赐教!!!!
╮(╯▽╰)╭