I can't get strcmp() to return 0 with the following code. please help..

char quit[10] = "q";
scanf(buf, "");
fgets (buf, 100,stdin);
fflush(stdin);
if(strcmp(quit, buf) == 0) {
    printf("Quiting program\n");
...

when I type 'q' into the command line it should enter that if statement, but it doesn't.

@OP

Try this:

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

int main(void) 
{
	char quit[10] = "q";
	char buf[10];

	fgets (buf, 100,stdin);

	if(strcmp(quit, buf) == 0) {
    		printf("Quiting program\n");
	}

	return 0;
}

For this purpose, i would rather do this :

if ( (key = getchar()) == 'q') {
     /* Your message */
}

Thanks for your reply, your code works so thanks.
I need it to be a string, because the user will enter a name or q to quit.

>> when I type 'q' into the command line it should enter that if statement, but it doesn't. fgets() stores the newline in the buffer, whenever there's enough room to do that. So, you are actually comparing strcmp("q", "q\n") , which apparently returns non-zero.

You might use e.g. strcspn() to get rid of this unwanted newline, like so ..

const char * quit = "q";
char buf[100] = "";

if(fgets(buf, sizeof(buf), stdin) != NULL) 
{ 
  /* If present, the trailing newline gets replaced with '\0' */
  buf[strcspn(buf, "\n")] = '\0';

  if(strcmp(quit, buf) == 0)
  {
    ... quit the program

P.S. fflush(stdin); may work with your current compiler, but horribly break on another one. An explanation and an alternative .. cprogramming.com FAQ

>I need it to be a string, because the user will enter a name or q to quit.

Ok. So, the first code i posted fine i guess.

This article has been dead for over six months. Start a new discussion instead.