从与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.

有其他人也,当然。