Welcome to our deep dive into the world of C Format Specifiers! In this comprehensive guide, we'll explore the various format specifiers used in C programming to handle different data types and structures. By the end, you'll be equipped with the knowledge to manipulate data effectively in your C programs. š
Before we delve into the format specifiers, let's ensure you have a basic understanding of some key C concepts:
int, float, char, etc.Format specifiers, also known as conversion specifiers, are used in the printf() and scanf() functions to handle different data types. They tell the compiler how to interpret the input or output data.
%d or %i - Decimal IntegerUsed for handling integer data, such as int and long int.
š Example:
#include <stdio.h>
int main() {
int number = 123;
printf("The number is: %d\n", number);
return 0;
}%f - Floating PointUsed for handling floating-point numbers, such as float and double.
š Example:
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("The value of Ļ is: %.2f\n", pi);
return 0;
}%c - CharacterUsed for handling individual characters, like char.
š Example:
#include <stdio.h>
int main() {
char letter = 'A';
printf("The character is: %c\n", letter);
return 0;
}%s - StringUsed for handling character arrays, also known as strings, defined as char[] or char *.
š Example:
#include <stdio.h>
int main() {
char message[] = "Hello, World!";
printf("The message is: %s\n", message);
return 0;
}%o - Octal IntegerUsed for handling octal (base-8) integers.
š Example:
#include <stdio.h>
int main() {
int number = 0123;
printf("The number in octal is: %o\n", number);
return 0;
}%x - Hexadecimal IntegerUsed for handling hexadecimal (base-16) integers.
š Example:
#include <stdio.h>
int main() {
int number = 0xAB;
printf("The number in hexadecimal is: %x\n", number);
return 0;
}%e and %E - Exponential Notation (e)Used for displaying floating-point numbers in exponential (scientific) notation.
š Example:
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("The value of Ļ in exponential notation is: %e\n", pi);
return 0;
}%g and %G - General FormatUsed to automatically choose between %e and %f, whichever is more appropriate for the given number.
š Example:
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("The value of Ļ in general format is: %g\n", pi);
return 0;
}Which format specifier is used for handling individual characters in C?
What does the `%s` format specifier handle in C?