C String Read

Scanf Syntax

To use scanf to read string from console we need to use %s.

Example 1

The following code uses scanf to read a string from console.


#include <stdio.h>
int main()// ww  w .ja  va  2s  .c o  m
{
   char me[20];
 
   printf("What is your name?");
   scanf("%s",&me);
   printf("Darn glad to meet you, %s!\n",me);
 
   return(0);
}

The code above generates the following result.

fgets Syntax

The standard function fgets can be used to read a string from the keyboard. The general form of an fgets call is:

fgets(name, sizeof(name), stdin);

The arguments are:

  • name is the name of a character array.
  • sizeof(name) indicates the maximum number of characters to read.
  • stdin is the file to read.

Example 2

Read a line from the keyboard and reports its length.


#include <string.h>
#include <stdio.h> 
//from w  w  w  . j  a v  a  2 s  .c o  m
int main() 
{  
    char line[100]; /* Line we are looking at */  
    printf("Enter a line: ");  

    fgets(line, sizeof(line), stdin);  

    printf("The length of the line is: %d\n", strlen(line));   

    return (0);
}  

The code above generates the following result.

Example 3

Ask the user for his first and last name.


#include <stdio.h> 
#include <string.h>
/*from   ww  w. jav a2 s.  c om*/
int main() {   
    char first[100];
    char last[100]; 
    char full[200];            

    printf("Enter first name: ");  
    fgets(first, sizeof(first), stdin);

    printf("Enter last name: ");   
    fgets(last, sizeof(last), stdin);  

    strcpy(full, first);   
    strcat(full, " "); 
    strcat(full, last);

    printf("The name is %s\n", full);  
    return (0);
}  

The code above generates the following result.





















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing