从 fgets() 输入中删除尾随换行符 [英] Removing trailing newline character from fgets() input

查看:64
本文介绍了从 fgets() 输入中删除尾随换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户那里获取一些数据并将其发送到 gcc 中的另一个函数.代码是这样的.

I am trying to get some data from the user and send it to another function in gcc. The code is something like this.

printf("Enter your Name: ");
if (!(fgets(Name, sizeof Name, stdin) != NULL)) {
    fprintf(stderr, "Error reading Name.
");
    exit(1);
}

但是,我发现它最后有一个换行符 .因此,如果我输入 John,它最终会发送 John .如何删除 并发送正确的字符串.

However, I find that it has a newline character in the end. So if I enter John it ends up sending John . How do I remove that and send a proper string.

推荐答案

优雅的方式:

Name[strcspn(Name, "
")] = 0;

有点丑的方式:

char *pos;
if ((pos=strchr(Name, '
')) != NULL)
    *pos = '';
else
    /* input too long for buffer, flag error */

有点奇怪的方式:

strtok(Name, "
");

请注意,如果用户输入空字符串(即仅按 Enter),strtok 函数将无法按预期工作.它使 字符完好无损.

Note that the strtok function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the character intact.

当然还有其他的.

这篇关于从 fgets() 输入中删除尾随换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆