Cover Image for Control String in C Language
104 views

Control String in C Language

The control strings in C are used in the printf and scanf functions to format the input and output of data. Control strings consist of format specifiers that define how the data should be displayed or read. Here’s an overview of control strings in C:

printf Control String:

In the printf function, control strings are used to format the output. They consist of format specifiers that begin with the percent sign (%) followed by a character that indicates the type of data being formatted. Here are some commonly used format specifiers:

  • %d: Format as a signed decimal integer.
  • %f: Format as a floating-point number.
  • %c: Format as a character.
  • %s: Format as a string.
  • %x or %X: Format as a hexadecimal number (lowercase or uppercase).
  • %o: Format as an octal number.

Example of using control strings with printf:

C
int number = 42;
float floatNumber = 3.14;
char character = 'A';
char string[] = "Hello, world!";

printf("Integer: %d\n", number);
printf("Float: %f\n", floatNumber);
printf("Character: %c\n", character);
printf("String: %s\n", string);

scanf Control String:

In the scanf function, control strings are used to format the input. They also consist of format specifiers that correspond to the data type you’re reading. Here are some commonly used format specifiers:

  • %d: Read a signed decimal integer.
  • %f: Read a floating-point number.
  • %c: Read a character.
  • %s: Read a string (stops at whitespace).
  • %x: Read a hexadecimal number.
  • %o: Read an octal number.

Example of using control strings with scanf:

C
int number;
float floatNumber;
char character;
char string[100];

printf("Enter an integer: ");
scanf("%d", &number);

printf("Enter a floating-point number: ");
scanf("%f", &floatNumber);

printf("Enter a character: ");
scanf(" %c", &character);  // Notice the space before %c to consume the newline character

printf("Enter a string: ");
scanf("%s", string);

printf("You entered: %d, %f, %c, %s\n", number, floatNumber, character, string);

Control strings allow you to control the formatting and reading of data in C’s input and output functions. Make sure to use the appropriate format specifiers for the data type you are working with to ensure correct behavior.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS