• C

The difference between scanf() and getline()

I have been playing around with scanf() and getline() and I notice that there is a difference in strings. Take a look at the following code:

#include <stdio.h>

int main()
{
  int bytes_read;
  int nbytes = 100;
  char *my_string;
  char *other;

  other = (char*) malloc(100);

  puts ("Please enter a line of text.");

  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, stdin);

  if (bytes_read == -1)
    {
      puts ("ERROR!");
    }
  else
    {
      puts ("Please enter the same text again: ");
      scanf("%s", other);

      puts("\nLength of first string:");
      printf("%d", strlen(my_string));
      puts("\nLength of Second string:");
      printf("%d", strlen(other));
     
      if(my_string == other)
        {
                puts("\nMATCH");
        } else {
                puts("\nNO MATCH");
        }
    }

  return 0;
}

Now, lets say I input 'string' for both prompts and here is my output:
Please enter a line of text.
Please enter the same text again:

Length of first string:
7
Length of Second string:
6
NO MATCH

Now, my question is, first, why are the two strings not matching eventhough I input the same thing for both. And two, how do I make them match and get rid of the extra space or garbage character produced by the getline() function.

Thanks,
Igor
igor92128Asked:
Who is Participating?
 
brettmjohnsonConnect With a Mentor Commented:
There are many differences:

scanf("%s") will read chars upto, but not including whitespace.
if your line is:
hello world
then scanf("%s") will return "hello"

getline returns an entire line, including the newline at the end.
(newline is considered whitespace by scanf).

By your example output. I suspect you entered a single word
(no spaces) at each prompt.  The difference in length is because
the getline return includes the newline character and the scanf
return does not.  These differences are clearly stated in the man
pages for the calls.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.