Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 135 ยท Projects

Project: Quiz Game

Build a quiz game in C: load questions from a text file with careful parsing, then shuffle questions and answers, validate input and score with a speed bonus.

A quiz game has little logic and a lot of data handling, which is why it is a good project. The questions should not live inside the program: if adding a question means recompiling, nobody will add questions. So they sit in a plain text file that anyone can edit, and the program has to read that file, check it, and cope with the mistakes people make when they edit files by hand.

The project uses structures, file reading, string functions, random numbers, time and fgets-based input. There are two stages: loading and validating the question bank, then the game itself with shuffling, scoring and a time bonus.

Stage 1: a question bank from a file

The file format. One question per line, with fields separated by a vertical bar, since a bar almost never appears in a question:

TEXT
question|option 1|option 2|option 3|option 4|number of the correct option

Blank lines are ignored, and a line that starts with # is a comment. These two small rules make the file much nicer to maintain, and they cost two if statements.

Parsing without strtok. strtok is the usual tool for splitting, but it changes hidden global state, collapses empty fields (so a||b would look like two fields) and is not safe to nest or use from threads. Splitting by hand with strchr is only a few lines: find the next bar, overwrite it with '\0' so the field becomes its own string, and continue after it. The function split_fields fills an array of pointers into the line buffer, so nothing is copied until the data has been validated. It stops at six fields. If a seventh bar exists, it stays inside the last field, where the number check below will reject it.

Validation is most of the work. parse_question checks, in order, that there are exactly six fields, that no text is too long for its array, that the question and options are not empty, and that the last field is a whole number from 1 to 4. For that last check it uses strtol with an end pointer, as described in string conversions: atoi would turn 3x or banana into a number without any complaint. The function returns 0 and sets *why to a message, and the loader prints the line number with it. Error messages that say "line 6: the answer must be a number from 1 to 4" are what turns a frustrating file format into a usable one.

Long lines. fgets stops when the buffer is full, leaving the rest of the line for the next call. That would turn one long line into two garbage lines. The loader notices (no newline in the buffer, and not at the end of the file), reports the line as too long, and reads and throws away the rest of it.

A sample file. Because every run of this page starts in an empty directory, Stage 1 begins by writing a small question file, which also shows fputs to a file. The sample has a comment, a blank line, and one broken question on purpose, so you can see the loader skip it and carry on.

C Stage 1: write, load and validate a question file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The line numbers in the message count the comment and blank lines too, because they refer to the file as an editor shows it. The marked option (*) is the one the file says is correct. Change the 9 in the broken line to 2, and a sixth question appears.

Stage 2: shuffling, scoring and timing

Shuffling with Fisher-Yates. To ask the questions in a random order, the game does not move structs around. It shuffles an array of indexes 0 .. n-1, and the game then asks bank[order[i]]. Sorting or shuffling small integers is cheaper than copying 260-byte structs, and the bank itself stays untouched. The algorithm walks from the end: for position i, pick a random j from 0 to i and swap them. Every possible order is equally likely. The common beginner shortcut (swap each element with a random position in the whole array) produces a biased result, and it is a classic bug.

Shuffling the options too. If the right answer is always the second option in the file, players learn that quickly. So each question gets its own small permutation of {0, 1, 2, 3}. Showing option number k means printing option[perm[k]], and the correct choice is wherever perm[k] equals answer - 1. The game computes that position once per question.

Reading a choice. read_choice returns a number from 1 to 4, or -1 if the input ended. Anything else (a letter, 5, an empty line) prints a hint and asks again. Using strtol with an end-pointer check again means 2x is rejected. The read loop echoes each line it reads, so the answers appear in the output on this page; in a real terminal your own typing is already visible, so you would remove the echo.

Scoring and the time bonus. A correct answer scores 10 points. If it arrived within 10 seconds of the question being shown, there is a bonus of 5. The program takes time(NULL) before the prompt and after the answer and subtracts them with difftime. This has a limit worth knowing: standard C cannot interrupt a blocked fgets, so the clock can only be checked after the player presses Enter. A true countdown needs select/poll, or a thread, which are platform features. On this page the answers arrive instantly, so every correct answer gets the bonus; in a terminal, wait for 11 seconds before answering and the bonus disappears.

The ending. After the last question, the game prints the score out of the maximum possible and a short verdict. The maximum is computed from the number of questions asked, not typed in as a constant, so it stays right when the bank grows. The seed is fixed (srand(11)) so the page always plays the same game. Use srand((unsigned)time(NULL)) for a game that changes each time.

C Stage 2: the full quiz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The input contains two bad answers on purpose (x and 5), which ask again without using up a question. The first, second and fourth questions are answered correctly and the other two are not. With this seed the right options are 3, 3, 1, 1 and 2, in order, so changing the input to those five numbers gives a perfect 75. Because the options are shuffled, the right position changes from question to question; try another srand seed and the answers move.

Ideas for going further

  • Categories and difficulty. Add a seventh field for a category, take it from the file, and let the player choose one from a menu.
  • Show the right answer's explanation. Add an optional eighth field with a sentence shown after a wrong answer.
  • A high-score table. Save the best five scores to a file, with names, using the binary approach from the library project.
  • A real countdown. On Linux or macOS, use poll on file descriptor 0 with a timeout, so the question can expire while the player is still thinking.
  • Never repeat a question. Remember which questions each player has already seen between games, in a file.
  • Better shuffle seeds. Mix time and the process id into the seed to make two games started in the same second differ.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the loader use strtol with an end pointer for the answer field instead of atoi?

    atoi returns 0 or a partial number without telling you the text was bad. strtol tells you where it stopped, so the whole field can be checked.
  2. 2. Why does the game shuffle an array of indexes instead of the array of struct Question?

    Struct assignment works, but copying a struct of about 260 bytes at every swap is wasteful. An index array is a light view over the data.
  3. 3. In Fisher-Yates, what range should the random index j have for position i?

    Choosing j from the not-yet-fixed part (0..i) gives every order the same probability. Swapping with a position from the whole array gives a biased shuffle.
  4. 4. Why can the time bonus only be checked after the player presses Enter?

    fgets waits until a line arrives. A real countdown needs platform features such as poll or select with a timeout, or another thread.
  5. 5. What does strchr(line, '\n') == NULL && !feof(f) detect after an fgets call?

    If fgets filled the buffer before reaching a newline and the file has more data, the rest of the line is still waiting. The loader reports it and discards the rest.

Summary

  • Keep content in a data file and make the format simple: one record per line, a separator, # comments and blank lines allowed.
  • Split fields by hand with strchr and '\0' when you need empty fields to stay empty; validate every field before storing it.
  • Check numbers with strtol and its end pointer, and report errors with the line number.
  • Handle over-long lines explicitly, because fgets splits them silently.
  • Shuffle an array of indexes with Fisher-Yates (j from 0..i), and shuffle answer positions per question.
  • Standard C cannot interrupt a blocking read, so a time bonus is measured after the answer and a true countdown needs poll or threads.

Next: the lexical analyzer project, where you read source code instead of a question file.