Reputation: 11
I don't understand why am I getting (null) after running this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char input;
printf("enter string: ");
scanf("s", input);
printf("%s", input);
}
Why am I getting (null) after scanf?
Upvotes: 1
Views: 827
Reputation: 2791
The problem in your answer is that you have a char variable input
, but it is not initialized with a length. As a result, it prints (NULL)
. To overcome this issue, you should change your declaration of input
to something like:
char input[30];
This way, you can store up to 30 chars in your input
variable. Note that I used 30 as an example; you can use any value of your choice here.
Secondly, the line:
scanf("s", input);
Is invalid; it should be:
scanf("%s", input);
Because %s
is a placeholder for the variable given after the string; here it is input
. %s
refers to a placeholder for a string or char[] data-type s is the correct syntax.
** As an aside, since you want to read an entire sentence as input, you should know that your code will only work for accepting input until a spacebetween the first word and the next one, because scanf()
does not read a space. To learn more anout using strings, refer to this link: C Programming Strings
Good luck!
Upvotes: 2
Reputation: 13
Try giving a length for yout char, i.E. char[25]. The char now keeps a single character.
Upvotes: 1