Use scanf() to read Strings - C Language Basics

C examples for Language Basics:scanf

Introduction

To read a string with the scanf( ) function, specify the %s format specifier.

%s on scanf() will read characters until it encounters a white-space character.

The white-space character is either a space, a newline, a tab, a vertical tab, or a form feed.

gets() reads a string until ENTER is pressed.

scanf( ) reads a string until the first white space is entered.

You cannot use scanf( ) to read a string like "this is a test" because the first space stops the reading process.

The following code shows how scanf() with %s work.

Demo Code

#include <stdio.h>

int main(void)
{
   char str[80];//from   w  w w .j a v a 2s .co m

   printf("Enter a string: ");
   scanf("%s", str);
   printf("Here's your string: %s", str);

   return 0;
}

Result


Related Tutorials