Reading in String and comparing it to C

Im trying to create a C-based string menu where the user enters a command and then a block of code is executed.

No matter what I do, the condition is not always true:

char *input= ""; fgets(input, 50, stdin); printf("%s",input); printf("%d",strcmp( input,"arrive\0")); if(strcmp( input,"arrive\0")==0){.... 

I am new to c and find lines that are really annoying.

What am I doing wrong?

Note: the current code resets my program: (

+4
source share
3 answers

Why strcmp always returns non-0:

strcmp returns 0 only when the lines are identical. As for why he always evaluates different. This is because fgets puts the newline character at the end of your input buffer until zero terminated.

 /*Will print 0 if you type in arrive<enter>*/ printf("%d",strcmp( input,"arrive\n")); 

Why your program crashes:

Another problem is that input must be a char buffer. For example: char input[1024]; You currently have input as a pointer to a null-terminated string (which is read-only)


Friendly suggestion:

Also, do not put the null end of \0 inside string literals. This is implied automatically when using a string literal. It doesn't matter to double the null termination to strcmp , but it can cause problems in your other future programs. And people will be wondering why you are doing double null termination.

+7
source

Try:

 #define BUFF_LEN 256 char input[BUFF_LEN]; fgets(input, BUFF_LEN, stdin); 

What you have *input is a pointer to a memory address that has not been allocated, so it cannot be used by your program. The result of using it, like you, is undefined, but usually leads to a segmentation fault . If you want to access it as a pointer, you first need to select it:

 char *input = malloc(BUFF_LEN); 

... of course, check that for failure (NULL), then free () is after you finish using it.

Edit:

At least according to a single UNIX specification , fgets () is guaranteed to terminate the zero buffer. It does not need to initialize input [].

As others have said, there is no need to include null / newlines when using strcmp ().

I also highly recommend that you get used to using strncmp() now, while starting to avoid many problems in the future.

+3
source

Try replacing the first line with

 char input[50]; memset(input, 0, sizeof(input)); 

Edit: However, the real problem is why strcmp does not return 0, you need to "trim" the line read from fgets, which in most cases includes a newline character.

+1
source

Source: https://habr.com/ru/post/971204/


All Articles