Input output string

There are several ways to take a string input from the console. We’ll see two different approaches to take string input.

First approach – using fgets()

#include <stdio.h>

int main() {

    char name[20];

    // Input using fgets
    printf("Enter your name : ");
    fgets(name, 20, stdin);

    printf("\nHello %s", name);

    return 0;
}

Output

Enter your name : Karan Mandal
Hello Karan Mandal

Explanation

The fgets() function reads the entire line including spaces and stores them to given buffer or character array. It stops reading at EOF or EOL.

You have to pass three arguments to fgets() function –

  1. First argument name of the character array variable (ex. name).
  2. Second is maximum size you want to read from console (ex. 20).
  3. And third is, from where you want to read, Here we are reading from standard input (stdin).

Second approach – using scanf()

#include <stdio.h>

int main() {

	char name[20];

	// Input using scanf
	printf("Enter your name : ");	
	scanf("%[^\n]%*c", name);

	printf("\nHello %s", name);

	return 0;
}

Output

Enter your name : Karan Mandal
Hello Karan Mandal

Explanation

The scanf() function with scanset expression [^\n]%*c does the same thing like fgets() function. With this expression scanf() reads everything until it reaches the newline character or EOL, but it ignores the new line character that means \n will not be inserted into the buffer.

Here you have to pass two parameters to the scanf() function –

  1. First argument is scanset expression as a string so that it can read chars including white spaces.
  2. Second argument is the name of character array variable.

Remember that while reading strings from console you don’t need to add & (address-of) operator with variable name.