This question already has an answer here:
I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE.
What I'm trying to do is reading a string (like "Barack Obama"
) and put it in a variable:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
Output:
Enter your name: Barack Obama
Your Name is: Barack
How can I make the program read the whole name?
Try this:
\n
just sets the delimiter for the scanned string.The correct answer is this:
That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.
Use:
100
is the max length of the buffer. You should adjust it as per your need.Use:
The
[]
is the scanset character.[^\n]
tells that while the input is not a newline ('\n'
) take input. Then with the%*c
it reads the newline character from the input buffer (which is not read), and the*
indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.Read here about the scanset and the assignment suppression operators.
Note you can also use
gets
but ....str
is the variable in which you are getting the string from.Using this code you can take input till pressing enter of your keyboard.
use
&
withscanf
input