We have already looked at how to output results to a screen with printf() statement.
Sometimes, you want to get inputs from human (e.g., how many times you want to run the simulation), and run the program with the inputs. So far, we have been modifying the source code to change values of variables or constants, recompile, and run.
#include <stdio.h> int main(void) { int popSize; double probability; printf("Type in a population size: "); scanf("%d", &popSize); printf("Type in a probability: "); scanf("%lf", &probability); printf("You typed in %d and %lf\n", popSize, probability); return 0; }
printf("Type 1 integer and 1 floating-point number: "); scanf("%d %lf", &popSize, &probability);When a user is typing in the inputs, the user can use whatever white spaces (spaces, tabs, or new lines).
You can type:
100 0.01
Or
100 0.01
or
100
0.01
If you type ls, you are seeing the message printed to stdout
on the screen.
When gcc complains, it is printing to stderr on the screen.
Analogy: FM radio has two output channels (right and left).
Analogy: This is similar to combining right and left channel (mono mode) and connecting to a single speaker (screen).
Analogy: you can connect another speakers or headphones to change the location of outputs.
fprintf(stderr, "ERROR: value of popSize is %d, should be positive\n", popSize);The first argument is the ``channel'' (file pointer) where you want to print. So the following 2 statements are equivalent.
fprintf{stdout, "Print this\n"); printf("Print this\n");
#include <stdio.h> int main (void) { FILE *outFP1; outFP1=fopen("outFileName1", "w"); if(!outFP1) { /* important to check that the file was opened successfully */ fprintf(stderr, "Can't open the file: %s\n", file); exit (-1); } fprintf(outFP1, "Write this to a file\n"); : fclose(outFP1); return 0; }The 2nd argument for fopen() is mode
"w" | write (you can write to this file) |
"r" | read only |
"a" | append mode (When you print out, they will be appended to the end of the file.) |
Make a program which will