从与fgets删除尾随换行符()输入 [英] Removing trailing newline character from fgets() input
本文介绍了从与fgets删除尾随换行符()输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从用户那里得到一些数据并将其发送给另一个函数在GCC。在code是这样的。
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.\n");
exit(1);
}
不过,我发现,它有一个新行 \\ n
字符结束。所以,如果我输入约翰
它结束了发送约翰\\ n
。我如何删除 \\ n
并发送正确的字符串。
However, I find that it has a newline \n
character in the end. So if I enter John
it ends up sending John\n
. How do I remove that \n
and send a proper string.
推荐答案
略带丑陋的方式:
char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
*pos = '\0';
略带奇怪的方式:
The slightly strange way:
strtok(Name, "\n");
注意,如果用户输入一个空字符串如预期的那样 strtok的
功能不起作用(即presses仅回车)。它离开 \\ n
字符不变。
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 \n
character intact.
有其他人也,当然。
这篇关于从与fgets删除尾随换行符()输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文