0
0
Cprogramming~5 mins

String input and output in C

Choose your learning style9 modes available
Introduction

We use string input and output to read words or sentences from the user and show text on the screen.

When you want the user to type their name.
When you need to display a message or sentence.
When you want to get a sentence or phrase from the user.
When you want to print text along with numbers.
When you want to show results or instructions to the user.
Syntax
C
char str[SIZE];

// To read a string
scanf("%s", str);

// To print a string
printf("%s", str);

Note: scanf("%s", str); reads a word (no spaces).

To read a full line with spaces, use fgets(str, SIZE, stdin); instead.

Examples
Reads a single word and prints a greeting.
C
char name[20];
scanf("%s", name);
printf("Hello %s!", name);
Reads a full line including spaces and prints it.
C
char sentence[100];
fgets(sentence, 100, stdin);
printf("You typed: %s", sentence);
Sample Program

This program asks the user to enter their name, reads it as a word, and then greets them by name.

C
#include <stdio.h>

int main() {
    char name[30];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("Hello, %s!\n", name);
    return 0;
}
OutputSuccess
Important Notes

Remember that scanf("%s", str); stops reading at the first space.

Use fgets() if you want to read sentences with spaces.

Always make sure the array size is big enough to hold the input plus the ending \0 character.

Summary

Use scanf("%s", str); to read a single word string.

Use printf("%s", str); to print a string.

Use fgets() to read full lines with spaces.