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

4

5

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string? (in C)

I am getting a problem using printf and fgets as in my code printf is written earlier then fget but it does not run, it runs after fgets runs.

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

int main( int argc, char ** argv ) {    
      printf("Type a String: ");
      fgets(string, max_string, stdin);
      printf("The String is %s\n", string);
      return 0;
}
Pyrophotometer answered 20/7, 2012 at 7:52 Comment(0)
I
7

do a flush of the stdout

fflush(stdout);

before fgets(...)

printf("Type a String: ");  
fflush(stdout);
fgets(string, max_string, stdin); 
Indwell answered 20/7, 2012 at 7:58 Comment(0)
G
1

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

Guerrilla answered 20/7, 2012 at 7:55 Comment(0)
S
1

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, ... .

Shabbygenteel answered 20/7, 2012 at 8:1 Comment(0)
F
0

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;
}
Fiddlefaddle answered 20/7, 2012 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.