Question

I am writing little program with a Shell like interface. My the ui is:

void cli_ui(void){
    bool loop = true ;
    char response[CHARSIZE];
    while (loop) {
    puts("cofre>");
    fgets(response, CHARSIZE, stdin);
    ....
    }

}

My problem with this is that the input is read after the prompt:

cofre>
# input is expected here

What I want is:

cofre> #input is expected here

How would you do this?

Was it helpful?

Solution

The problem is that puts() writes the string and replaces the trailing null by a newline, which results in a new line.

The answer is to use fputs(). Somewhat surprisingly, fputs() does not do the same as puts(), but instead outputs the string with no trailing newline. So.

fputs("cofre>", stdout);

Some people would suggest you use printf(), but this would be a mistake. When you use fgets() you should pair it with fputs(). The benefit is that you are explicitly using standard input and output, so you will be able to drive your REPL from a script.

Please be aware that in some implementations fgets() and fputs() may be buffered, and that is not what you want. In some cases you may need to use low level I/O such as cputs/cgets() instead. These are non-standard.

OTHER TIPS

puts() writes the string s and a trailing newline to stdout.

use

printf("cofre>");

You can use printf instead of puts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top