0
#include <stdio.h>
#include <string.h>
int main(){
    char name[20];
    printf("Whats your name: ");
    fgets(name,20,stdin);
    printf("hello, %s", name);
    if(strcmp(name, "john")==0){
        printf("hello john.");
    }
    return 0;
}

im a java developer an newly in C . why strcmp not working. help me please

1 Answers1

1

The problem is with the fgets. Fix the new line bug:

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

int fixedFgets(char str[], int n);

int main() {
    char name[20];
    printf("Whats your name: ");

    if (fixedFgets(name, 20))
    {
        printf("hello, %s\n", name);

        if (strcmp(name, "john") == 0) {
            printf("hello john.");
        }
    }

    return 0;
}

/*
    Function will perform the fgets command and also remove the newline
    that might be at the end of the string - a known issue with fgets.
*/
int fixedFgets(char str[], int n)
{
    int success = 1;

    // Check that fgets worked
    if (fgets(str, n, stdin) != NULL)
    {
         str[strcspn(str, "\n")] = 0;
    }
    else
    {
        success = 0;
    }

    return success;
}
Slack Bot
  • 64
  • 1
  • 9
  • 1
    What happens if `fgets` fails? – Neijwiert Jul 10 '19 at 12:49
  • Thank you very much. GOOD LUCK – someoneidontwanttosay Jul 10 '19 at 12:53
  • From the docs: "*If the stream is at end-of-file [...] fgets() shall return a null pointer.*" IF the user just pressed Ctrl-D (UNIX) or Ctrl-Z (Windows) EOF is set. – alk Jul 10 '19 at 12:59
  • ... which in turn mean nothing is read into `str` and this `str[strcspn(str, "\n")] = 0;` would invoke undefined behaviour and the program in the best case would just crash. – alk Jul 10 '19 at 13:03
  • The same would happen if input to the program had been redirect to an empty file. All in all `fixedFgets()` is good example how exactly ***not*** to do it, namely *not* to check the outcome of a relevant function call. – alk Jul 10 '19 at 13:06
  • Thanks for your point. You can add a simple `if (fgets(str, n, stdin) != NULL)` @alk – Slack Bot Jul 10 '19 at 13:06
  • *I* know this, but *you* give bad advise to the world. Please you fix your proposal. – alk Jul 10 '19 at 13:07
  • And in any case another call to `ferror()` is strongly recommended if `fgets()` returned `NULL`, to exactly distinguish between EOF and an error. – alk Jul 10 '19 at 13:09
  • Great. Thank you very much @alk – Slack Bot Jul 10 '19 at 13:10
  • The last change makes things even worth as the caller has no clue if the string passed in has successfully been set or not. – alk Jul 10 '19 at 13:15