Question

I’m trying to make a C program which is prompting the user to type a message from the console and then show that message the user has typed, as in the following example:

C:>promptTest
type your message >>>>  test
typed :  test

C:>

This is my code:

#include <stdio.h>
#include <string.h>
int main(){
    char msg[32];
    printf("type your message >>>>\t");
    fgets(msg,sizeof(msg),stdin);
    msg[strlen(msg) - 1] = '\0';
    printf("typed :  %s\n",msg);
    return 0;
}

It can be built on both Windows7 and CentOS and it can be run normally on Windows like above.

However, it can’t be run on CentOS. I mean nothing accepts any message from the prompt like below:

$ ./promptTest
type your message >>>>  test

typed :  
$ 

How can I fix this?

Here is information about my machine.

$ cat /etc/redhat-release
CentOS release 6.4 (Final)
$ 
$ arch
x86_64
$ 
Was it helpful?

Solution 2

I found the solution.

CL+LF coused this matter.

see Controlling prompt for command line

OTHER TIPS

strlen() returns size_t not int.

Printing size_t on a 64bit IXish system using %d might fail, as the former most likly is 64bit while the latter expects 32bit.

So at least on a 64bit IXish system instead of

printf("### buf(%d) = %s\n",strlen(buf),buf);
printf("### message(%d) = %s\n",strlen(message),message);

do

printf("### buf(%zu) = %s\n",strlen(buf),buf);
printf("### message(%zu) = %s\n",strlen(message),message);

As a (ugly) workaround you could also cast strlen() down to int.

printf("### buf(%d) = %s\n", (int) strlen(buf),buf);
printf("### message(%d) = %s\n", (int) strlen(message),message);

This workaround however assumes no string being longer then INT_MAX.

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