igor92128
asked on
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
#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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
https://www.experts-exchange.com/questions/21399633/The-difference-between-scanf-and-getline.html