Issue in C language using 'fgets' after 'printf' as 'fgets' runs before 'printf' [duplicate]

淺唱寂寞╮ 提交于 2019-12-01 20:56:34

do a flush of the stdout

fflush(stdout);

before fgets(...)

printf("Type a String: ");  
fflush(stdout);
fgets(string, max_string, stdin); 
neel

put a \n in printf statement. This might be the problem as in C buffers are line terminated.

Neel is right. If you want to just write something down without having to put that '\n' you can use the function write();

#include <stdio.h>
#include <unistd.h>
#include <string.h>

enum { max_string = 127 };
static char string[max_string+1] = "";


my_putstr(char *str)
{
     write(1, str, strlen(str));
}

int main( int argc, char ** argv ) {    
    my_putstr("Type a String: ");  
    fgets(string, max_string, stdin); 
    printf("The String is %s\n", string);
    return 0;
}

The point is not that printf runs after fgets, but instead that its output is displayed after it.

This happens because standard output (the file descriptor you're writing on with printf) is line-buffered, i.e. the standard library defers prints after a newline character (\n) has been received for printing.

From man stdout:

The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed.

To investigate different results, edit your example to use fflush, or print on standard error using fprintf(stderr, ... .

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!