[c] Reading string from input with space character?

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?

This question is related to c string input scanf whitespace

The answer is


#include <stdio.h>
// read a line into str, return length
int read_line(char str[]) {
int c, i=0;
c = getchar();
while (c != '\n' && c != EOF) { 
   str[i] = c;
   c = getchar();
   i++;
}
str[i] = '\0';
return i;
}

Here is an example of how you can get input containing spaces by using the fgets function.

#include <stdio.h>

int main()
{
    char name[100];
    printf("Enter your name: ");
    fgets(name, 100, stdin); 
    printf("Your Name is: %s", name);
    return 0;
}

The correct answer is this:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    // pay attention to the space in front of the %
    //that do all the trick
    scanf(" %[^\n]s", name);
    printf("Your Name is: %s", name);

    return 0;
}

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.


If you need to read more than one line, need to clear buffer. Example:

int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);

Using this code you can take input till pressing enter of your keyboard.

char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
    scanf("%c ", &ch[i]);
}

#include<stdio.h>
int main()
{
   char name[100];
   printf("Enter your name: ");
   scanf("%[^\n]s",name);
   printf("Your Name is: %s",name);
   return 0;
}

While the above mentioned methods do work, but each one has it's own kind of problems.

You can use getline() or getdelim(), 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.

#include <stdio.h>
#include<stdlib.h>

// s is a pointer to char type.
char *s;
// size is of size_t type, this number varies based on your guess of 
// how long the input is, even if the number is small, it isn't going 
// to be a problem
size_t size = 10;

int main(){
// allocate s with the necessary memory needed, +1 is added 
// as its input also contains, /n character at the end.
    s = (char *)malloc(size+1);
    getline(&s,&size,stdin);
    printf("%s",s);
    return 0;
}

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 using realloc().

So it doesn't matter how long your input is.

size is updated with no.of bytes read, as per above sample input size will be 27.

getline() also considers \n as input.So your 's' will hold '\n' at the end.

There is also more generic version of getline(), which is getdelim(), which takes one more extra argument, that is delimiter.

getdelim() is defined as:

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

Linux man page


Try this:

scanf("%[^\n]s",name);

\n just sets the delimiter for the scanned string.


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.

#include<stdio.h>
int main()
{
 int i,size;
 char a[100];
 fgets(a,100,stdin);;
 size = strlen(a);
 a[size-1]='\0';

return 0;
}

Update: Updated with help from other users.


scanf("%s",name);

use & with scanf input


"%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).


scanf(" %[^\t\n]s",&str);

str is the variable in which you are getting the string from.


"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;

#include <stdio.h>
int main()
{
    printf("Enter your name\n");
   char a[80];
   gets(a);
   printf("Your name is %s\n", a);
   return 0;
}

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to scanf

How to scanf only integer? Reading numbers from a text file into an array in C How can I read an input string of unknown length? Reading in double values with scanf in c How to do scanf for single char in C printf not printing on console How to find EOF through fscanf? How to read numbers separated by space using scanf Going through a text file line by line in C What is the format specifier for unsigned short int?

Examples related to whitespace

How to create string with multiple spaces in JavaScript git: fatal: I don't handle protocol '??http' Show whitespace characters in Visual Studio Code What is the symbol for whitespace in C? How to print variables without spaces between values Trim whitespace from a String How do I escape spaces in path for scp copy in Linux? Avoid line break between html elements Remove "whitespace" between div element How to remove all white spaces in java