Reputation: 1
I want to make a program to output a string that includes two words using scanf
and printf
functions.
This is my source code:
#include <stdio.h>
int main ()
{
char str[20];
scanf("%s%s", &str);
printf("%s", str);
return 0;
}
After I run the code the results are not what I want.
Input:
new version
Output:
new
What is the solution for this problem?
Upvotes: 0
Views: 704
Reputation: 23822
You can read an entire string including spaces using [^\n]
specifier, which means read everything in the input stream until a newline character is found.
#include <stdio.h>
int main ()
{
char str[100]; //20 characters is not much, addded a little more
scanf("%99[^\n]", str); //size limit 99 + null byte
printf("%s", str);
return 0;
}
Note that operator &
is not needed for char arrays in scanf
and the input should be limited to the size of the destination buffer to avoid buffer overflow.
A character is 1 byte, in today's machines, generally speaking, that amounts to almost nothing, so be more generous with your char
arrays if you can.
Upvotes: 3