C - Reading a string with scanf()

Introduction

The %s conversion character is used.

Demo

#include <stdio.h> 

int main() //from   ww w  .ja v a  2 s  .co  m
{ 
     char firstname[15]; 

     printf("Type your first name: "); 
     scanf("%s",firstname); 
     printf("Pleased to meet you, %s.\n",firstname); 
     return(0); 
}

Result

The code declares a char array - a string variable - named firstname.

The number in the brackets indicates the size of the array, or the total number of characters that can be stored there.

The array isn't assigned a value, so it's created empty. It sets aside storage for up to 15 characters.

The scanf() function reads a string from standard input and stores it in the firstname array.

The %s conversion character directs scanf() to look for a string as input, just as %s is a placeholder for strings in printf()'s output.

Related Topic