-2

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?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    It is not a compiler problem. The issue is that you didn't read the docs more closely. [The fgets function docs](http://en.cppreference.com/w/c/io/fgets). What do you think the second parameter does? – PaulMcKenzie Apr 25 '16 at 15:19
  • `fgets` and `cin>>a` do not result in the same string. Please read the documentation for _both_ to get a better understanding of what they do. – Captain Obvlious Apr 25 '16 at 15:20
  • @PaulMcKenzie as str will contain that newline character so it gives value 1. is it right? – Fahim Feroje Al Jami Apr 25 '16 at 15:33
  • @FahimFerojeAlJami - Yes, new lines are not stripped. Second, you could have discovered this yourself if you wrote a loop and outputted each character in `a` as an integer: `for (int i = 0; i < strlen(a) ++i) cout << static_cast(a[i]) << "\n";` Then you would see that there is an invisible control character at the end. That should have been your first step if there was something you didn't expect, and that is to see what the characters are that make up the `a` string. – PaulMcKenzie Apr 25 '16 at 15:38
  • @PaulMcKenzie thanks. I got it. – Fahim Feroje Al Jami Apr 25 '16 at 15:42

1 Answers1

1

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.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56