Popular Searches

Reject Input That Cannot Be a Purchase

CBeginner
Practice Now

Introduction

A receipt should contain approved purchases, not whatever a number-conversion function happens to recognize at the beginning of a line. Sunny Snacks now needs complete input validation and a capacity check that cannot overwrite earlier purchases.

This independent unit prepares its own catalog and receipt program. You need the arrays, functions, structs and integer-cent receipt work from Keep Every Line of the Receipt. You will learn only the string/address details needed for a bounded decimal parser, then reject bad input without changing the basket. The WebIDE file editor, Workspace terminal and compiler are ready; this is a synthetic text-receipt program, not a payment system. Time is an author estimate.

Convert Complete Decimal Text

In this step, you will first observe a normal numeric conversion, expose its prefix-only limitation, and implement the success/failure boundary in the shared parser function.

Start in Workspace. This independent lab has its own prepared files. cd enters the working directory and ls lists its contents:

cd /home/labex/project/receipts
ls

The file examples/parse-prefix.c is a small observation example, not the purchase parser. Compile it and pass the text 2 as one command-line argument. An argument after the executable name is text supplied by the shell, not an answer to an interactive prompt. The flags select C11 and warnings; -o names the executable.

gcc -std=c11 -Wall -Wextra examples/parse-prefix.c -o parse-prefix
./parse-prefix 2

Expected output:

Converted prefix: 2
Remaining text: []

The empty brackets show no remaining characters after this ordinary number. Predict the next result before running it: will the conversion reject the letters, or return the number at the beginning and stop before them?

./parse-prefix 2bars

Expected output:

Converted prefix: 2
Remaining text: [bars]

The number 2 was converted, but the whole text was not a valid quantity. This demonstration exits normally after displaying a conversion; status 0 and a numeric result do not mean a purchase is valid. Print its last exit status immediately, before another command replaces it:

echo $?

The expected output is 0. A legal alternative spelling also converts normally:

./parse-prefix +0002

It prints the same prefix 2 and empty remainder as the first run. This example intentionally lacks full-text, conversion-overflow, business-range and output-preservation checks. Use only these small observation inputs; do not reuse this program as the final parser or treat it as a general validator. Running it does not complete either lab check.

Make a local backup before editing. mkdir creates the backup directory; cp copies the listed files into the final directory argument:

mkdir before-edit
cp till.c parse.h catalog.h driver.h read-line.h parse-demo.c examples/parse-prefix.c before-edit/

Switch to WebIDE. Use File > Open Folder... to open /home/labex/project/receipts and use View > Explorer if the file list is hidden. Before the first edit in this independent lab, open File and inspect Auto Save. If it has a check mark, click Auto Save to turn it off. Open File again and confirm Auto Save is not checked, then press Escape. This makes saving and abandoning edits explicit; do not rely on the setting from another lab. After File > Save, wait until the unsaved dot on the file tab disappears before switching to Workspace. Expand examples and open parse-prefix.c. Its main receives an argument count and an array of argument strings; argv[1] is the one text argument used above. strtol attempts a conversion and the example prints both its result and the unconsumed text. Read this example without editing it.

Open parse-demo.c next. Unlike the observation program, this supplied caller reads a complete input line, passes it to parse_number, prints an accepted quantity or a rejection, then exits. The same parse.h will also be included by till.c in the next step. Open parse.h: its function currently returns 0 for every input, so even valid input is rejected. Keep catalog.h, driver.h, read-line.h, parse-demo.c and the observation example unchanged; edit only parse.h and later till.c.

In C, text is a character array ending with the zero-valued NUL terminator, written \0. This is different from the visible digit '0':

text:  '2' '0' '\0'
index:  0   1    2

Open read-line.h to understand its contract, without rewriting it. The supplied read_line reserves 64 bytes: up to 63 input bytes plus the terminator. getchar() reads one character; its int result can also represent EOF. The loop stores up to 63 characters but keeps reading an overlong line through its newline, so leftovers never become the next answer. It returns 1 for a complete line, -1 for a drained overlong line, or 0 for EOF. EOF also discards an unfinished line. The demo's read_line(text) != 1 rejects the latter two cases before conversion.

Return to parse.h and find parse_number using Edit > Find, Enter and Escape. Its public interface is:

static int parse_number(const char text[], int minimum, int maximum, int *result)

Keep the name and parameter order because both prepared callers use them. Return 1 on success and 0 on failure. On success, put the converted integer into the caller's result variable; on failure leave that variable unchanged. minimum and maximum are inclusive. Numeric 0 is valid when minimum is 0, even though a purchase quantity has minimum 1.

Read the call in parse-demo.c again. A normal integer argument passes a value. &quantity means the address of the caller's quantity storage slot. Parameter int *result receives that address; *result = value writes into the caller's slot. The star in a declaration describes a variable holding an address; in an expression it accesses the slot at that address. We use these specific output parameters, not dynamic allocation or a general pointer exercise.

strtol, declared in stdlib.h, converts text to a long integer. Pass base 10 explicitly, so leading zero remains decimal. Its first argument points to the first character to read. Its second argument is another output: char *end will hold the address of the first character that did not belong to the number. &end passes the address of that address-holding variable so strtol can update it; it does not copy a second string.

input:  2 b a r s \0
          ^
          end points here after strtol returns 2

Now list the cases your real parser must distinguish. The syntax allows optional leading/trailing ASCII spaces or Tabs, an optional sign and decimal digits including leading zeros. Internal spaces, decimal points, hexadecimal prefixes, other whitespace and trailing letters are invalid. Blank or sign-only text is invalid. Exact lowercase done belongs only to the program's Product ID prompt, not numeric parsing.

Use an array index begin to skip only the allowed leading spaces/Tabs. &text[begin] is the address of the first remaining character. Before calling strtol, require a digit or sign so its broader whitespace handling cannot silently widen our syntax. After conversion, end == &text[begin] means no digit was consumed. *end reads the character at the stopping address; end++ advances that address by one character. Skip only allowed trailing spaces/Tabs, then require the terminator.

The text may also represent a number too large for long. errno, from errno.h, is the library's error indicator. Reset it to zero before the call; ERANGE afterward indicates range overflow. Check that error and the inclusive business minimum/maximum before converting long to int. A returned numeric zero alone is not an error signal.

Return to parse.h. Keep the two include lines, the existing function signature and its outer braces. Select only the placeholder statements inside parse_number, from (void)text; through return 0;. Implement the checks in this order, with the only write to the caller placed last:

    int begin = 0;
    while (text[begin] == ' ' || text[begin] == '\t') begin++;
    char first = text[begin];
    if (first != '+' && first != '-' && (first < '0' || first > '9')) return 0;
    char *end;
    errno = 0;
    long value = strtol(&text[begin], &end, 10);
    if (end == &text[begin] || errno == ERANGE) return 0;
    while (*end == ' ' || *end == '\t') end++;
    if (*end != '\0' || value < minimum || value > maximum) return 0;
    *result = (int)value;
    return 1;

The final *result = (int)value writes the caller's integer only after every check passes. The explicit cast (int) performs the now-safe conversion. The header function is static, so it belongs to each program that includes it. Save with File > Save, return to Workspace and compile the interactive demo:

gcc -std=c11 -Wall -Wextra parse-demo.c -o parse-demo
./parse-demo

At Quantity (1..20):, enter +0002 and press Enter. Expect Accepted quantity: 2 and a return to the shell. This time you entered text at a program prompt, not as a shell argument.

Run again:

./parse-demo

Enter 2bars. Expect Rejected quantity.: prefix conversion is no longer enough. This rejection is intentional and the caller returns status 2. Immediately print that status:

echo $?

Expected output is 2. The terminal and compiler have not failed. Run a third time:

./parse-demo

Enter 9999999999999999999999999999999999999999 and press Enter. It also rejects: this line is shorter than 63 bytes, but its number overflows the conversion range. In contrast, 21 fits a long but fails the quantity maximum 20. These are different reasons for a safe rejection.

If compilation names parse.h, return to that file in WebIDE rather than editing parse-demo.c to hide the error. Use Go > Go to Line/Column... with GCC's first line number and inspect the preceding statement too. Save and recompile before rerunning. Both callers include the header during compilation; an old binary cannot test a new header edit. To discard an unsaved wrong-file edit, close its editor tab and choose Don't Save. For a saved mistake, use Undo and Save, or close that tab, restore only the affected file from before-edit with the taught cp pattern, then reopen it. Do not rerun setup or overwrite unrelated progress.

Approve a Purchase Before Changing State

In this step, you will connect the parser to the purchase array, reject a full basket before writing, and save a complete receipt after several rejected inputs.

Start in Workspace, in /home/labex/project/receipts. This unit's till.c already contains the record definitions, catalog lookup and complete printer from the first lab. Only its approval function needs implementation; do not recopy or rewrite the prepared printer.

cd /home/labex/project/receipts
cat catalog.h

Switch to WebIDE. Open driver.h to read its actual calls; do not edit it. No special read-only editor mode is needed. It reads a complete ID line, recognizes exact done, parses a decimal ID and checks whether the product exists. It then reads a quantity and calls your parser with bounds 1..20. In both calls, &id or &quantity passes an output address; the parser you saved writes that variable only on success. !parse_number(...) means the parser returned false. An overlong input line is drained and refused, and a failed conversion returns to Product ID without calling approval. EOF instead cancels the current run with status 2 and no completed receipt. A bad quantity discards only the pending candidate, not earlier approved purchases.

Now open till.c and find approve_purchase with Edit > Find, Enter and Escape. Read the nearby basket and count definitions. Its job is to protect the array before changing either field or the count. Usable positions are 0 through 5. Writing once to basket[MAX_LINES] is already outside the array; refusing later does not undo that access.

List the three reasons to refuse here: an absent product, quantity outside 1..20, or line_count >= MAX_LINES. || means any of those conditions is sufficient. Only after all pass should you write the product reference and quantity, increment the count and return 1. A legitimate zero price must not be mistaken for an invalid quantity.

Leave the function signature and outer braces intact. Select only its placeholder statements, from (void)id; through return 0;, and implement this body. Keep print_receipt, the type definitions, lookup and driver include in place.

    int index = find_product(id);
    if (index < 0 || quantity < 1 || quantity > MAX_QUANTITY || line_count >= MAX_LINES)
        return 0;
    basket[line_count].product_index = index;
    basket[line_count].quantity = quantity;
    line_count++;
    return 1;

Review the order before saving: refusal precedes the first array write, and the count increases only for an approved line. All calculations remain integer cents. The four catalog rows have IDs 1..999 and prices 0..9999 cents, including a valid free item. Six quantities of at most 20 bound the total at 1,199,880 cents. Every approved purchase remains separate and ordered, even when an ID repeats. The same logic must work after recompilation with another supplied four-row catalog in these bounds. Internal struct and local names can vary; the callable interfaces still need to match the driver.

Choose File > Save, return to Workspace and compile. This recompiles the included parse.h as well as till.c; the older parse-demo binary and this new executable are separate callers.

gcc -std=c11 -Wall -Wextra till.c -o till

If GCC reports an error, use its file name and first line number in WebIDE, inspect the affected statement and the preceding punctuation, save and recompile. Do not run an old executable after failed compilation. The saved parser and this approval body must both be present in the compiled program.

The driver writes prompts and messages to standard error. Only a completed receipt goes to standard output. Redirect it to the new required output file and keep responding at the visible prompts:

./till > receipt.txt

Enter this transaction in order, pressing Enter after each ID and quantity. An unknown ID does not ask for a quantity. After rejection you return to Product ID; do not keep answering the previous quantity prompt.

Product ID input Quantity input Expected observation
101 2 Added line 1
102 2bars Quantity rejected; line 1 retained
999 Not requested Unknown ID; line 1 retained
103 20 Added line 2, valid upper quantity bound
104 1 Added line 3, valid free product
102 1 Added line 4
101 1 Added line 5, separate from line 1
104 2 Added line 6
103 1 Basket-full rejection; all six lines retained
done Not requested Complete the receipt; return to the shell

Only after the shell prompt returns, read the actual file:

cat receipt.txt

Expected contents:

SUNNY SNACKS
ID | ITEM | QTY | UNIT | SUBTOTAL
101 | Oat bar | 2 | 1.25 | 2.50
103 | Water | 20 | 0.75 | 15.00
104 | Water | 1 | 0.00 | 0.00
102 | Fruit cup | 1 | 2.30 | 2.30
101 | Oat bar | 1 | 1.25 | 1.25
104 | Water | 2 | 0.00 | 0.00
TOTAL | 21.05

Rejected 2bars, ID 999 and the seventh purchase created no rows and changed no earlier row. IDs 103 and 104 display Water but keep different prices. A zero price is not a zero quantity. The integer sum is 250 + 1500 + 0 + 230 + 125 + 0 = 2105 cents.

The completed receipt contains the shop title, the five named bar-separated columns, every purchase in order and exactly one final TOTAL. Blank lines and field-surrounding spaces may vary, but a missing header, unknown extra records or rows after the total are incomplete output. Keep receipt.txt, till.c, parse.h, executable till and all supplied files. The course check also runs unchanged source copies with runtime bounds detection in a disposable directory. It detects errors exercised by those inputs, not complete memory safety, and does not repair your files.

To observe cancellation separately from checkout, start another transaction with a different output name:

./till > cancelled.txt

Enter ID 101, press Enter, then press Ctrl+D at the empty quantity prompt. EOF cancels with Cancelled: no receipt. and publishes no completed receipt. It also discards a partial unfinished input line. Immediately read the native exit status:

echo $?

Expected output is 2. The earlier receipt.txt remains because this command uses another file name. > would truncate an old file of the same name before C runs. By contrast, done at Product ID completes with status 0, including an empty receipt whose total is 0.00; done is never a quantity command.

The reader accepts exactly 63 bytes before newline and drains a longer line before refusing it; its leftovers cannot become another answer. A rejected quantity returns to Product ID and abandons only that pending candidate. If a legitimate purchase is rejected, inspect the full-text/inclusive-range checks in parse.h, then the approval guard in till.c. If earlier rows disappear, inspect whether the error path changes the array or count before returning. Correct only the relevant local implementation in WebIDE, save, recompile and replay the required transaction from an empty new run. Do not edit receipt text. The reusable program and saved receipt must agree.

Summary

You used a bounded character line, conversion end pointer, overflow check and inclusive business bounds before approving a purchase. Your program preserved all earlier lines after bad input and a full-basket rejection, while zero-price products and boundary quantities remained usable. Checkout and EOF now have clear, different results.