Common mistakes with input and output
Comments and questions to John Rowe.
|
Wrong
| Right
|
printf("Number of atoms?\n");
scanf("%d\n", &j);
|
printf("Number of atoms?\n");
scanf("%d", &j);
|
Since scanf() is an intelligent function: it
skips over white space such as spaces and new-lines unless we
actively stop it. Such as the next mistake...
|
For example, putting a comma after "%d" when reading two integers:
|
Wrong
| Right
|
printf("Numbers required?\n");
scanf("%d, %d", &j, &k);
|
printf("Numbers required?\n");
scanf("%d %d", &j, &k);
|
Note, this isn't always wrong
(for example we may be reading from a file with a fixed
data format), but we should avoid it if possible.
|
|
Wrong
| Right
|
scanf("%d", &j);
|
printf("Number of atoms?\n");
scanf("%d", &j);
|
Again, this isn't always wrong but in general it's
much better to tell the user what they are supposed to be entering.
|
For variety we show a situation where we choose to warn of
the failure to open a file rather than exit the program:
|
Wrong
| Right
|
outfile = fopen("helloworld.txt", "w");
fprintf(outfile, "Hello, world\n");
fclose(outfile);
|
outfile = fopen("helloworld.txt", "w");
if ( outfile != NULL ) {
fprintf(outfile, "Hello, world\n");
fclose(outfile);
}
else {
fprintf(stderr, "Could not open helloworld.txt\n");
}
|
You only need to worry about these if you have not
followed our advice...
|
Forgetting the ampersand
|
Wrong
| Right
|
printf("Please enter the mass\n");
scanf("%lg", mass);
|
printf("Please enter the mass\n");
scanf("%lg", &mass);
|
Not using %lg to read a double
|
Wrong
| Right
|
printf("Please enter the mass\n");
scanf("%g", &mass);
|
printf("Please enter the mass\n");
scanf("%lg", &mass);
|
Log in