String Input/Output (I/O)

String Input/Output (I/O) in C language is used to read and write strings of characters to and from the input/output devices. The standard I/O library in C provides functions for performing string I/O operations.

The following are some of the commonly used functions for string I/O in C:

fgets()

This function is used to read a string of characters from the standard input device (usually the keyboard) and store it in an array. It takes three arguments: the name of the character array to store the input, the maximum number of characters to read, and the input stream.

char str[100];
fgets(str, 100, stdin); // reads a string of characters from the keyboard and stores it in str

fputs()

This function is used to write a string of characters to the standard output device (usually the screen). It takes two arguments: the name of the character array to write and the output stream.

char str[] = "Hello, world!";
fputs(str, stdout); // writes the string "Hello, world!" to the screen

scanf()

This function is used to read formatted input from the standard input device (usually the keyboard). It takes a format string as its first argument, which specifies the format of the input, and reads the input values accordingly.

char str[100];
scanf("%s", str); // reads a string of characters from the keyboard and stores it in str

printf()

This function is used to write formatted output to the standard output device (usually the screen). It takes a format string as its first argument, which specifies the format of the output, and writes the output values accordingly.

char str[] = "Hello, world!";
printf("The string is %s", str); // writes the string "The string is Hello, world!" to the screen

Note that string I/O operations in C are usually buffered, which means that the characters are stored in a buffer before being read or written to the input/output device. The buffer is flushed (i.e., the characters are written to the device) either when the buffer is full, when a newline character (\n) is encountered, or when the program terminates.

Also, be careful when using the gets() function for string input, as it does not check the length of the input string and can lead to buffer overflows. The fgets() function is a safer alternative, as it allows you to specify the maximum number of characters to read.

Add a Comment

Your email address will not be published. Required fields are marked *