Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Common mistakes
Back to top
On this page
Contents

Common mistakes with input and output

Putting a newline at the end of the format string

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...

Putting other characters in the format string

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.

Silent input requests

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.

Not checking the result of fopen()

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");
  }

Mistakes detectable with advanced compiler warnings

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);

                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top