Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3281
  • Last Modified:

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
0
igor92128
Asked:
igor92128
1 Solution
 
brettmjohnsonCommented:
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now