Monday, December 29, 2008

Getting input

For programming competitions, input will usually come from standard input; that is, input is taken from the user manually typing the input, or input is directed into the program from a file.


When input is manually typed by the user, it will be like Figure 1.




Figure 1. Input manually typed by the user.


In Figure 1, the user manually types the input “User is typing this line now.”

When input is directed into the program from a file, it would appear like Figure 2.




Figure 2. Input directed from a file.


In Figure 2, the contents of the file i.txt are inputted into the program.

Reading a line from standard input can be done using Code 1.


Code 1. Reading a line from standard input.

#include "stdio.h"

int main() {

__char line[100];


__fgets(line, 100, stdin);


__return 0;

}


In Code 1, the fgets statement is configured to read from standard input using the stdin parameter. The line read is then placed into the character array line. The parameter 100 is used to indicate the maximum number of characters to be read. We use 100 since we declared the line variable to be a character array of 100 slots.


In Code 1, once the fgets statement is executed, the user can pretty much do anything with the line variable which contains the line read from standard input. For example, the user can print the contents into standard output such as the code in Code 2.


Code 2. Printing what was read from standard input.

#include "stdio.h"


int main() {

__char line[100];


__fgets(line, 100, stdin);

__printf("User typed the following: %s\n" , line);


__return 0;

}


When Code 2 is executed, it behaves like Figure 3.



Figure 3. Sample execution of Code 2.

No comments:

Post a Comment