Monday, February 8, 2016

String Input/Output

The string is nothing but an array of characters. Similar as character I/O, C have standard library functions for input/output operations of strings. They are gets(char *s) and puts(const char *s).
To read a string from standard input, use gets()as give below.
  1. char string[20];
  2. gets(string);
gets reads string into the passed character array until a newline or EOF is encountered in the standard input. For instance, it reads all the characters and save it in the passed character array until you press "enter" key.
To write a string to the standard output, use puts()as give below.
  1. char string[] = "This is a string.";
  2. puts(string);
puts writes a string to standard output until a string terminator is encountered. 

Example of String Input/Output

  1. #include<stdio.h>
  2. void main()
  3. {
  4. char s[100];
  5. printf("Enter a string: ");
  6. gets(s);
  7. puts(s);
  8. }
  9.  
  10. Output:
  11. Enter a string: This is a string
  12. This is a string
The above program reads a line as input and prints the line into the screen.

No comments: