问题是,当您输入名称如elvis(有5个字母)时,它会打印出来:
Please enter your name.
elvis
Your name is elvis
and it is 6 letters long.
Press any key to continue . . .
问题是它产生了另一个不必要的行,因为在elvis之后我按下了回车。
很抱歉,对于这些规则的新用户,请更正我并教育我,谢谢您的时间。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define STR_LEN 7
int main(void)
{
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));
system("PAUSE");
return 0;
}
答案 0 :(得分:3)
fgets
总是在末尾写下'\ n'字符,如果它适合(当然,看到它)。所以你需要手动删除它。
(我知道,因为我已经向大学的同学们说了20次:/)
您需要检查最后一个字符是否为'\ n',如果是,则删除它(用0 =='\ 0'覆盖)。一些示例代码:
char str[256];
fgets(str, 256, stdin);
if (*str && str[strlen(str)-1] == '\n')
str[strlen(str)-1] = 0;
(请注意,上面的代码假设GCC优化了纯函数调用。如果不是,则应将长度保存在单独的变量中以优化程序)
答案 1 :(得分:2)
正如同伴们已经告诉你的那样, fgets 从文件指针(在你的情况下为stdin)中获取字符,为 name 添加一个额外的'\ n'。 您可以轻松地删除它,如
name[strlen(name)-1] = '\0';
始终在plalen(名称)上将printf格式化为%lu 而不是%d。
也是一个很好的提示,请务必检查功能返回时的错误。 请在发布此处之后,始终咨询linux man (fgets stdlib func),尝试一些示例,调试它们,搜索和阅读google即使在堆栈溢出上你还有一个很好的搜索选项。(这不是讨厌,只是一个友好的一般建议)。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define STR_LEN 7
int main(void)
{
char name[10] = {0};
printf("Please enter your name.\n");
if (!fgets(name ,10, stdin)) {
printf("Error reading from stdin");
return 1;
}
size_t len = strlen(name);
if (len > 0 && name[len-1] == '\n') {
name[len-1] = '\0';
}
printf("Your name is %s and it is %lu letters long.\n" , name , strlen(name));
system("PAUSE");
return 0;
}
编辑:( melpomene建议)。