C String Input/Output šŸŽÆ

beginner
17 min

C String Input/Output šŸŽÆ

Welcome to the exciting world of C String Input/Output! In this lesson, we'll dive deep into understanding how to work with strings, their input, and output in C programming. Let's get started! šŸ“

What are Strings in C? šŸ’”

In C, a string is an array of characters, terminated by a null character \0. Strings can be input using various functions, and output can be displayed using different functions as well.

Understanding Input Functions šŸ“

scanf() Function šŸ“

scanf() is a function used for inputting data in C. To read a string, we use the %s format specifier in scanf().

c
#include <stdio.h> int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); printf("You entered: %s", str); return 0; }

šŸ’” Pro Tip: Always make sure to have a sufficient size array to store the input string, as the scanf() function doesn't account for the null character \0.

fgets() Function šŸ“

fgets() is another function used for inputting data, offering more control over the input. It reads up to a specified number of characters from a stream.

c
#include <stdio.h> int main() { char str[100]; printf("Enter a string (less than 100 characters): "); fgets(str, sizeof(str), stdin); printf("You entered: %s", str); return 0; }

Displaying Output šŸ’”

printf() Function šŸ“

printf() is a function used for outputting data in C. To display a string, we use the %s format specifier in printf().

c
#include <stdio.h> int main() { char str[] = "Hello, World!"; printf("%s", str); return 0; }

Practical Application šŸ’”

Let's create a simple program that asks for a user's name, greets them, and displays a farewell message.

c
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s! Nice to meet you.\n", name); printf("Goodbye, %s! See you soon.\n", name); return 0; }
Quick Quiz
Question 1 of 1

What function is used for reading a string in C?

Quick Quiz
Question 1 of 1

What function is used for displaying a string in C?