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! š
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.
scanf() Function šscanf() is a function used for inputting data in C. To read a string, we use the %s format specifier in scanf().
#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.
#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;
}printf() Function šprintf() is a function used for outputting data in C. To display a string, we use the %s format specifier in printf().
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("%s", str);
return 0;
}Let's create a simple program that asks for a user's name, greets them, and displays a farewell message.
#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;
}What function is used for reading a string in C?
What function is used for displaying a string in C?