简体   繁体   English

fgets在C linux中不起作用

[英]fgets not working in C linux

I always feel lots of problem while taking char or string inputs in C linux. 在C linux中使用char或string输入时,我总是会遇到很多问题。 And see this prog. 并查看此编。 It's not taking input from the user. 它不接受用户的输入。 Please help. 请帮忙。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char *buf;
    int msglen;
    printf("\nEnter message length\t");
    scanf("%d",&msglen);       

    buf=malloc(msglen);

    //memset(buf,'\0',msglen+1);
    printf("\nEnter data\t");
    fflush(stdin);
    fgets(buf,msglen,stdin); //NOT WORKING

    fputs(buf,stdout);
    return 0;
}   

Thanks :) 谢谢 :)

fflush() is used to flush the output streams and not clear the remaining characters from stdin . fflush()用于刷新output streams ,而不清除stdin剩余的字符。 use gets() or getchar() first to remove the EOF from stdin 首先使用gets()getchar()stdin删除EOF

使用getchar()代替fflush() ,它可以工作。

When you read the integer with scanf("%d"....) , it does not remove the newline from the input stream. 当您用scanf("%d"....)读取整数时,它不会从输入流中删除换行符。 So when you call fgets later, it reads and finds a newline , ie you read a blank line. 因此,当您稍后调用fgets ,它将读取并找到一个换行符,即您读取了一个空行。

To read the next line instead you will need to consume that newline, eg getchar() as someone else suggested. 要读取下一行,您将需要使用该换行符,例如,其他人建议使用的getchar()

This sort of issue is common when you mix formatted I/O ( scanf ) with unformatted I/O. 当您将格式化的I / O( scanf )与未格式化的I / O混合使用时,这种问题很常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM