C , fgets() 在尝试扫描字符串时扫描额外的字符

标签 c

问题是当你输入一个名字如 elvis(有 5 个字母)时,它会打印出这个:

Please enter your name.
elvis
Your name is elvis
 and it is 6 letters long.
Press any key to continue . . .

问题是它产生了另一行不必要的行,那是因为在 elvis 之后我按下了 enter。

很抱歉成为新用户,我对这些规则很陌生,请指正并教育我,感谢您的宝贵时间。

#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;
}

最佳答案

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 优化了纯函数调用。如果不是,您应该将长度保存在单独的变量中以优化程序)

关于C , fgets() 在尝试扫描字符串时扫描额外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535735/

相关文章:

c++ - CC2538 (Cortex m3) 启动时出现硬故障,位于 __lib_init_array 中

C Initializer元素不是常量[数组和变量有什​​么区别]

c - 基于链表的 Infix 计算器中的错误

c - 用于重构数组的正则表达式

c - 宏作为另一个宏的参数

c - Scanf() 在特定情况下表现奇怪

c - C 中的二叉搜索树。

ProC 中使用和不使用游标的 SQL 查询比较

c - 生成不重复的随机数。我的逻辑正确吗?

c - 在 while 循环中使用函数(在 Atom 中有效,但在 VIM 中无效)