与fgets()包括在最后的换行符 [英] fgets() includes the newline at the end

查看:338
本文介绍了与fgets()包括在最后的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果我键入quit,它不退出程序;我不知道为什么是这样的情况。

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

顺便说一句输入声明为的char *输入;

推荐答案

在您输入尾随的换行符。请参见人FGETS 。测试跳槽换行+,例如:

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

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


我完全错过了最后一句话,再的char *输入。根据不同的架构,输入将有4个或8个字节长。因此,code是有效


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

fgets(input, 8, stdin);

这并不反映内存的实际大小,输入点。这可能工作,只要输入大于八个字节短,但会截断输入,如果是较大的。此外,您将在您下次调用时获得输入其余与fgets

which doesn't reflect the real size of memory, input points 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.

您应该要么放弃,真正的大小或采取@ JonathanLeffler的意见,并声明一个字符数组来代替,例如

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

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

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

这篇关于与fgets()包括在最后的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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