C and C++ Programming Resources

Share/Bookmark
Custom Search

Input and Output

Posted on September 10th, 2008

Reading a Line

The line input functions read a line from an input stream. They read all characters up to the next newline character ‘\n’. The standard library has two line input functions, gets() and fgets().

The gets() Function

This is a straight forward function, reading a line from stdin and storing it in a string. The function prototype is

char *gets(char *str);

gets() takes a pointer to type char as its argument and returns a pointer to type char. The gets() function reads characters from stdin until a newline (\n) or end-of-file is encountered; the newline is replaced with a null character, and the string is stored at the location indicated by str.

The return value is a pointer to the string (the same as str). If gets() encounters an error or reads end-of-file before any characters are input, a null pointer is returned.

Before calling gets(), we must allocate sufficient memory space to store the string. This function has no way of knowing whether space pointed to by ptr is allocated; the string is input and stored starting at ptr in either case. If the space hasn’t been allocated, the string might overwrite other data and cause program errors.

Using gets() to input string data from the keyboard.
 /* Demonstrates using the gets() library function. */

 #include <STDIO.H>

 /* Allocate a character array to hold input. */

 char input[81];

 main()
 {
 puts("Enter some text, then press Enter: ");
 gets(input);
 printf("You entered: %s\n", input);

 return 0;
 }
Enter some text, then press Enter:
This is a test
You entered: This is a test

In this example, the argument to gets() is the expression input, which is the name of a type char array and therefore a pointer to the first array element. The array is declared with 81 elements in line 7. Because the maximum line length possible on most computer screens is 80 characters, this array size provides space for the longest possible input line (plus the null character that gets()
adds at the end).

The gets() function has a return value. gets() returns a pointer to type char with the address where the input string is stored. This is the same value that is passed to gets(), but having the value returned to the program in this way lets your program test for a blank line.

Using the gets() return value to test for the input of a blank line.
/* Demonstrates using the gets() return value. */

 #include <STDIO.H>

 /* Declare a character array to hold input, and a pointer. */

 char input[81], *ptr;

 main()
 {
 /* Display instructions. */

 puts("Enter text a line at a time, then press Enter.");
 puts("Enter a blank line when done.");

 /* Loop as long as input is not a blank line. */

 while ( *(ptr = gets(input)) != NULL)
 printf("You entered %s\n", input);

 puts("Thank you and good-bye\n");

 return 0;
 }
Enter text a line at a time, then press Enter.
Enter a blank line when done.
First string
You entered First string
Two
You entered Two
Asfia Firdaus
You entered Asfia Firdaus
Thank you and good-bye

If we enter a blank line (that is, if we simply press Enter) in response to line 18, the string (which contains 0 characters) is still stored with a null character at the end. Because the string has a length of 0, the null character is stored in the first position. This is the position pointed to by the return value of gets(), so if we test that position and find a null character, we know
that a blank line was entered.

The fgets() Function

The fgets() library function is similar to gets() in that it reads a line of text from an input stream. It’s more flexible, because it lets the programmer specify the specific input stream to use and the maximum number of characters to be input. The fgets() function is often used to input text from disk files. To use it for input from stdin, we specify stdin as the input stream. The prototype of fgets() is

char *fgets(char *str, int n, FILE *fp);

The last parameter, FILE *fp, is used to specify the input stream. Simply specify the standard input stream, stdin, as the stream argument.

The pointer str indicates where the input string is stored. The argument n specifies the maximum number of characters to be input. The fgets() function reads characters from the input stream until a newline or end-of-line is encountered or n – 1 characters have been read. The newline is included in the string and terminated with a \0 before it is stored. The return values of fgets() are the
same as described earlier for gets().

Strictly speaking, fgets() doesn’t input a single line of text (if you define a line as a sequence of characters ending with a newline). It can read less than a full line if the line contains more than n -1 characters. When used with stdin, execution doesn’t return from fgets() until you press Enter, but only the first n-1 characters are stored in the string. The newline is included in the string only if it falls within the first n-1 characters.

Using the fgets() function for keyboard input.
/* Demonstrates the fgets() function. */

 #include <STDIO.H>

 #define MAXLEN 10

 main()
 {
 char buffer[MAXLEN];

 puts("Enter text a line at a time; enter a blank to exit.");

 while (1)
 {
 fgets(buffer, MAXLEN, stdin);

 if (buffer[0] == `\n')
 break;

 puts(buffer);
 }
 return 0;
 }
Enter text a line at a time; enter a blank to exit.
Roses are red
Roses are
red
Violets are blue
Violets a
re blue
Programming in C
Programmi
ng in C
Is for people like you!
Is for pe
ople like
you!

Line 15 contains the fgets() function. When running the program, enter lines of length less than and greater than MAXLEN to see what happens. If a line greater than MAXLEN is entered, the first MAXLEN – 1 characters are read by the first call to fgets(); the remaining characters remain in the keyboard buffer and are read by the next call to fgets() or any other function that reads from stdin. The program exits when a blank line is entered (lines 17 and 18).

Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4] [Page - 5] [Page - 6]

Tags: , , , , ,

Like What you See?

Become one of the regulars by subscribing! You'll be the first to know when we add more great posts just like this. Join up by either RSS Feeds or Email Updates today!

There are 154 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.

  • Hackersh says:

    I really want to write a prog that will write to an open page in Microsoft word……..any info

  • Rivera says:

    i want a program thats prompts the user to input an integer and then output the number with the digit reserved.for example if input is 12345, the output should be 54321.

    • Speedy says:

      I dont have C/C++ compiler now. So, giving a code which will work… guess syntax error wont be there

      #include<stdio.h>
      #include<string.h>
      #include<conio.h>
      void main()
      {
      static char a[1000];
      int i=0,n=0;
      printf("Enter the number:");
      gets(a);//if any error occurs, in this line use a=gets();
      n=strlen(a);
      for(i=n-1;i>=0;i--)
      {
          printf("%c",a[i]);
      }
      getch();
      }
      

      ——– Original Message ——–
      i want a program thats prompts the user to input an integer and then output the number with the digit reserved.for example if input is 12345, the output should be 54321.

    • sme lng;-> says:

      #include
      main()
      {
      int n,r;
      clrscr();
      printf(”
      Enter a number:”);
      scanf(“%d”, &n);
      for(; n != 0 ;) {
      r= n%10;
      printf(“%d”, r);
      n= n%10;
      }
      getch();
      }

  • cestinaline says:

    How to write a program that will compute and display the midterm grade of student.
    the midterm grade is equal to 1/3 of the minor A exam and 2/3 of the midterm exam.

  • Hari says:

    i am doing cgi programming.. during server processing,instead of write some details to a temp file i want ot use stdin -stdout.
    what i planed is like….

    exec 1>&0 # redirect stdout to stdin
    system(“ls”) # it will write o/p to stdin
    while(fgets(line,sizeof(line),stdin)!=NULL)
    puts(line);

    but things not working properly…

  • bishwendu says:

    i want a simple project in c language with complete explanation of various commands or syntax used.Level of the project being B.Tech(fifth sem).Please it is urgent as matter relates to on campus placements.It is really important.kindly email me at bishwendu029@gmail.com.please!!!!!!!!

  • Demkish says:

    Hi, is there anyone who can help me make a program in C in which if we enter a month and day the program will outputs a zodiac sign. Please help me I need it badly…:-(

  • Ali says:

    hi is there any one who know about c language Abook or site that can be usefull for bigginer becouse I realy need it.
    Thanks

  • Clarence_L says:

    Please Help Me Onegai i need an output i will put 5 numbers that will set in ascending and descending order using array in c++ thnx in advance please i really in need….

  • miiszarniie says:

    write a C program that will create a 3×3 matrix & compute for the sum of columns & sum of rows.

  • jamz2008 says:

    4.Input the amount of purchase, which is less than P100.00. Calculate the Change with the following breakdown:

    P50.00 – _______;
    P20.00 – _______;
    P10.00 – _______;
    P 5.00 – _______;
    P 1.00 – _______;

    PLEASE HELP ME WITH THIS

  • laarni says:

    How to write a program that will compute and display the midterm grade of student.
    the midterm grade is equal to 1/3 of the minor A exam and 2/3 of the midterm exam.please help me for the code i need it 2mrw.plz email me add dj_bendz67@yahoo.com for the code.tnx

  • scarletdream says:

    how to change the output to input in C++….the another’s program output works as an input…can everybody help me?


Leave a Reply

You must be logged in to post a comment.