Search code examples
c++fgetscinstrcmp

Output does not match strcmp() function in c


For comparing two strings by a strcmp() function i took one input string by fgets() and cin and another is given in function as default argument . But when i compare them by strcmp() funtion outputs does not match.

    char a[20];
    int b;
    cin>>a;
    b=strcmp(a,"ab");
    cout<<b;

where i take input a as ab and b's value is 0 which is completely fine.But when for the same input is taken by fgets() then strcmp() output is not same as before.

char a[20];
    int b;
    fgets(a,sizeof(a),stdin);
    b=strcmp(a,"ab");
    cout<<b;

where a's value is ab and b's value is 1. Why? is that a compiler problem or something else?


Solution

  • fgets() does not strip any newline, per section 7.21.7.2 The fgets function of the C standard:

    The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s . No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.