当我使用fgets时,如果输入的字符串较短,则输入的最大字符串长度也会输入到该字符串中。
例如
char name[10] = {0};
printf("Please enter your name.\n");
fgets(name, 10, stdin);
printf("Your name is %s and it is %d letters long.\n", name, strlen(name));
input: elvis output: Your name is elvis and it is 6 letters long.
*我知道该怎么做,但我正在寻找最短的方法
答案 0 :(得分:-1)
name[strlen(name) - 1] = 0;
应该足够快,因为以后您仍然需要找到name
的长度。
char name[10] = {0};
size_t len;
printf("Please enter your name.\n");
fgets(name, 10, stdin);
name[(len = strlen(name)) - 1] = 0;
printf("Your name is %s and it is %zu letters long.\n", name, len);