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?
Here is an example of how you can get input containing spaces by using the
fgets
function."%s"
will read the input until whitespace is reached.gets might be a good place to start if you want to read a line (i.e. all characters including whitespace until a newline character is reached).
While the above mentioned methods do work, but each one has it's own kind of problems.
You can use
getline()
orgetdelim()
, if you are using posix supported platform. If you are using windows and minigw as your compiler, then it should be available.getline()
is defined as :ssize_t getline(char **lineptr, size_t *n, FILE *stream);
In order to take input, first you need to create a pointer to char type.
Sample Input:
Hello world to the world!
Output:
Hello world to the world!\n
One thing to notice here is, even though allocated memory for s is 11 bytes, where as input size is 26 bytes, getline reallocates
s
usingrealloc()
.So it doesn't matter how long your input is.
size
is updated with no.of bytes read, as per above sample inputsize
will be27
.getline()
also considers\n
as input.So your 's' will hold '\n' at the end.There is also more generic version of
getline()
, which isgetdelim()
, which takes one more extra argument, that isdelimiter
.getdelim()
is defined as:ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
Linux man page
NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.
Update: Updated with help from other users.
"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;