C语言 fgets() 在末尾包含换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13443793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:28:22  来源:igfitidea点击:

fgets() includes the newline at the end

cstringfgets

提问by Man Person

fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
  exit(-1);
}

If I type quit, it does not exit the program; I'm wondering why this is the case.

如果我输入quit,它不会退出程序;我想知道为什么会这样。

By the way inputis declared as char *input;.

顺便input声明为char *input;

采纳答案by Olaf Dietsche

Trailing newline in your input. See man fgets. Test for "quit" + newline, for example:

输入中的尾随换行符。参见man fgets。测试“退出”+换行符,例如:

fgets(input,sizeof(input),stdin);
if(strcmp(input, "quit\n") == 0){
    exit(-1);
}


I completely missed the last sentence, re char *input. Depending on the architecture, inputwill be 4 or 8 bytes long. So the code is effectively

我完全错过了最后一句话,re char *input。根据体系结构,input长度为 4 或 8 个字节。所以代码是有效的

fgets(input, 8, stdin);

which doesn't reflect the real size of memory, inputpoints to. This might "work" as long as the input is shorter than eight bytes, but will truncate the input, if it is larger. Furthermore, you will get the rest of the input the next time you call fgets.

这并不反映内存的实际大小,input指向。只要输入短于八个字节,这可能“有效”,但如果输入较大,则会截断输入。此外,您将在下次调用时获得其余的输入fgets

You should either give the real size or take @JonathanLeffler's advice and declare a char array instead, e.g.

您应该给出实际大小或接受@JonathanLeffler 的建议并声明一个字符数组,例如

char input[64];
fgets(input, sizeof(input), stdin);

or

或者

char *input = malloc(N);
fgets(input, N, stdin);

回答by codaddict

The function fgetsmight add a newline at the end of the string read. You'll have to check that:

该函数fgets可能会在读取的字符串末尾添加换行符。你必须检查:

size_t ln = strlen(input) - 1;
if (input[ln] == '\n')
    input[ln] = '
strtok(input, "\n");
';

or even

甚至

if(strstr(input, "quit") != NULL){

回答by Jonathon David White

Suggest you code this as:

建议您将其编码为:

for (i = 0; input[i] != '
while(fgets(message,80,stdin))
{
    l=strlen(message)-1;
    if(message[l]='\n') message[l]='##代码##';
            else message[i+1]='##代码##';
}
'; i++); /* getting the string size */ input[i-1] = '##代码##'; /* removing the newline */

Reason: This will solve issue of people adding extra characters (e.g. space before or after text).

原因:这将解决人们添加额外字符的问题(例如文本前后的空格)。

回答by csr-nontol

This solution only needs the standard library (stdio.h) and gives the same results.

此解决方案只需要标准库 (stdio.h) 并给出相同的结果。

##代码##

回答by Madan Ram

what i did is to replace newline by '\0' null .

我所做的是用 '\0' null 替换换行符。

##代码##