The reliable way to disregard bad values in C before you use data is to reject them at the boundary: read into a wide, checked type, test every conversion and range condition, and only then copy the value into your working variable. Never "fix" input in place and hope it was valid. The core condition is simple — a value counts as usable only when parsing succeeded, the magnitude is within the field's documented range, and it is consistent with the format the source promises. Everything else should be skipped, defaulted, or treated as an error, depending on what your program is doing with the data.

This guide covers the practical patterns: reading numbers, filtering arrays, cleaning strings, skipping rows and fields, and separating "bad data" from "bad program logic." It assumes standard C (C99 and later are fine), no external libraries, and no browsing — the examples are self-contained and you can compile each one.

Decide what "incorrect" means before you write any code

Disregarding values is a decision, and the decision needs a definition. In C you will meet at least five different kinds of "incorrect," and each has a different remedy:

Unparseable text. "12abc" or "1.2.3" read as a number. The conversion stopped early or overflowed; the value is not a number at all. Out-of-range but well-formed numbers. A temperature of 900°C, an age of −4, a percentage of 150. Syntactically fine, semantically impossible for the field. Missing values. An empty field, "N/A", or a sentinel like −999 that the producer used for "no reading." These are not errors in the same sense, but they must not be averaged or compared as if real. Stale or duplicate records. Valid individually, but repeated or superseded. Disregarding these is a filtering rule about records, not values. Wrong-typed data. Binary garbage read as text, endianness mismatches, a struct field interpreted at the wrong offset. This is usually a format bug, not a data-quality problem, and masking it will hide the real fault.

Write the rule down in one place. A field like percent might be defined as: valid only if parsing fully consumed the token, the value is in [0, 100], and the token was not empty. Once that sentence exists, the code writes itself and reviewers can check it. If the rule lives only in your head, some code path will eventually use a value you meant to reject.

A second decision matters just as much: what happens to a rejected value? Three answers are common. Skip the record or field entirely (count it, log it, move on). Substitute a documented default and flag it. Abort the operation with an error when the data is required for correctness. Choose per field, and be consistent. Silently substituting zero is the most dangerous option because zeros propagate: a rejected price of 0 skews an average exactly as badly as the bad price did.

Prerequisites: a wide type, a strict conversion, and an error channel

Before touching real data, set up three things.

A wide enough working type. If a field is documented as a 16-bit count, parse into long or long long and range-check afterward. strtol returns long, which is at least 32 bits on every mainstream platform; that gives you room to detect overflow beyond your field's real limits rather than losing it inside a narrow type.

A conversion function that reports failure. The strto* family — strtol, strtoll, strtoul, strtod — is the correct tool for text-to-number work. They set errno to ERANGE on overflow/underflow, and they give you an end pointer so you can see whether the whole token was consumed. atoi does neither; it cannot distinguish "0" from "garbage" and has no defined behavior on overflow. Do not use it for data you intend to validate.

A place to put the verdict. A function that returns both a value and a status avoids the classic ambiguity where 0 means "valid zero" or "failed." A small struct works well:

The success check is built into the return: if (r.ok) use(r.value); else count_reject();. If you skip any one of those five tests you get a specific failure mode: drop the end == s check and empty strings become zero; drop the errno check and huge inputs wrap into plausible-looking numbers; drop the trailing-junk check and "12abc" silently becomes 12; drop the range check and 900°C passes through.

Two details worth knowing. strtol skips leading whitespace by itself, so " 42" parses to 42 — usually what you want for text data, but if a space is meaningful in your format, check the first character before calling it. And if you are parsing unsigned quantities, use strtoul/strtoull and remember they accept a leading minus sign with wraparound semantics; for data validation, reject any token whose first non-space character is - rather than relying on the conversion.

Reading streams and lines without trusting the input

Most bad data arrives as lines of text from a file, a pipe, or a network socket. fgets is the safe line reader; it takes a buffer size and never overflows, but it splits overlong lines. The detection trick is to check whether the last character read is a newline: if it is not and you have not hit end-of-file, the line was too long and the remainder is still in the stream. You must then drain the rest of the line, or that remainder will be parsed as a fresh record — one of the most common ways garbage becomes data.

A -1 return is your "disregard this record" signal: count it, log the line number, and continue. The stop condition here is different from numeric validation — a truncated line usually means the buffer is too small for the format, which is a program configuration problem, not bad source data. If it happens frequently, enlarge the buffer or switch to a length-aware reader rather than "fixing" the parser.

For field-separated data (CSV and similar), resist the urge to call strtok on the original line and parse in place. strtok writes NUL bytes over the delimiters, so after the first pass you can no longer re-read the line to log what was rejected, and it cannot represent empty fields. Copy each token into a fixed-size scratch buffer of its own, then validate that copy:

This example is deliberately plain. Real CSV allows quoted fields containing commas, escaped quotes, and embedded newlines; if your source can contain those, you need a state machine that tracks quote parity, not strchr. The validation principle doesn't change — the point is that each field gets its own bounded copy and its own verdict.

Disregarding bad values inside arrays and structs

When data is already in memory — an array of readings, a struct full of sensor fields — "disregarding" becomes a question of representation. You cannot make a slot disappear from a C array, so use one of three patterns and stick to it.

A validity flag per record. The most explicit option, and the one I'd recommend for anything that will be read by someone else:

Averages and comparisons then skip on the flag, not on a magic value. This pattern survives changes in what counts as bad, because the flag records that a decision was made at validation time rather than relying on a later reader to re-derive it.

Compact the array. Filtering in place is a two-index walk: one index reads every element, the other writes only the survivors. This preserves order and needs no allocation:

The returned count is essential: after compaction the array's old length is a lie, and iterating to the original n will process stale copies. The success check is w <= n plus a count of rejects, and you can assert that rejects printed by your logging equal n - w.

A parallel sentinel, used carefully. Marking cells with NAN from <math.h> works for floating-point arrays because NAN != NAN by IEEE 754 rules, so x == x is false exactly for sentinels. But sentinels leak. Any code that does not check will happily sum them, and the sum becomes NAN too. Prefer flags in structs; reserve NAN for tight numeric buffers where every consumer is written to test isnan(). And do not invent your own sentinel like −9999 for integer data without documenting it at the definition — classic −999 missing-value conventions cause exactly the "bad value treated as real" problem you're trying to prevent.

For floating-point text, the same rules apply with strtod. One trap is locale: strtod honors the current locale's decimal separator, so in a comma-decimal locale "1,5" parses as 1 with trailing junk. If your data format is fixed to a period, call strtod and additionally reject any token containing a comma before the end pointer, or set the program's locale explicitly with setlocale(LC_NUMERIC, "C") at startup and document that decision. Also reject inf, infinity, and nan spellings unless your format genuinely allows them; strtod will accept them and they will poison arithmetic.

Strings: rejecting text before it reaches logic

Text fields carry their own incorrectness: embedded NUL bytes, overlong values, unexpected characters, and trailing whitespace that breaks lookups. The boundary method is the same — measure, test, and copy only when acceptable.

A practical note on trimming: if you decide to strip trailing spaces, do it before validation and then validate the trimmed copy, not the original. Validating one string and storing another is how "bad" values slip through — for instance, a token that passes your character check before you strip an embedded tab. Also decide explicitly whether an empty string is a valid field ("no comment") or a rejection; most downstream bugs come from that ambiguity rather than from exotic characters.

For identifiers and codes (country codes, enum-like keys), the cheapest correct approach is an allowlist. A short array of known-good strings plus a full-string compare (strcmp, not strstr) rejects typos, wrong case, and injected suffixes in one test. Whatever is not in the list is disregarded and logged, and the log is how you discover new legitimate codes instead of guessing.

When to substitute a default instead of skipping

Skipping is not always possible. A configuration file with one malformed line still needs the rest of the settings; a required field might need a documented fallback. In those cases, substituting is legitimate if three conditions hold: the default is documented where the field is defined, the substitution is reported (a counter, a log line, or a status flag returned to the caller), and the default is chosen so it cannot silently pass for real data. A missing-port default of 8080 is a policy; a missing-threshold default of 0 might disable a safety check, so it should instead be an abort.

The pattern that keeps this honest is the "applied defaults" list returned alongside the parsed configuration. Callers can then print how many defaults were applied, and tests can assert that a file with two bad lines yields two reports. Without that channel, a substituted default is indistinguishable from a value the user actually wrote, which is precisely the failure that "disregarding incorrect values" is supposed to prevent.

Worked estimate: what skipping does to your results

Suppose a reader expects 1,000 temperature readings and your validation rule (say, −50°C to 60°C, plus a documented −999 sentinel for missing) rejects 40 of them: 25 sentinels and 15 out-of-range spikes. If the 25 sentinels were ordinary missing values the producer always emits, excluding them is correct and your usable denominator is 975; if they were meant to represent real measurements, excluding them biases the sample toward non-missing hours, and you need to say so. Similarly, if the 15 spikes all came from a mis-scaled sensor (values near 900), their exclusion changes the mean by a lot less than including them would — 15 values of 900°C among 1,000 readings near 20°C would drag the mean from roughly 20°C to about 33°C, while excluding them keeps it near the true range. The accounting rule is: report the count of each rejection reason, not just the total, because "number discarded" hides which kind of absence you created. All of these figures are illustrative; the point is to keep the denominator explicit and reproducible rather than letting rejection silently redefine what "average" means.

Testing and failure modes to expect

The way to know your disregard logic works is to feed it the inputs that break it, and to watch specific symptoms.

Empty and whitespace-only tokens should be rejected, not become zero. If they become zero, you are likely calling atoi or skipping the end == s check. "12abc", "12.0" read as an integer, and "1e9" read as an integer should be rejected or handled per the documented format. If "12abc" becomes 12, you are not checking *end. Huge values like "99999999999999999999999" should be rejected via errno == ERANGE, not wrap to a small positive number. Overlong lines should be flagged and drained; if the tail of a 10,000-character line shows up as a separate record, your reader lacks the truncation check. Signs where none are allowed, commas where periods are expected, and inf/nan should each have a test case with the expected verdict written next to it. Boundary values — the exact minimum and maximum of each field's range, one below and one above — are the four cases that catch off-by-one range errors (<= versus <).

The clean way to run these is a table of inputs and expected ok/value pairs, applied to the parse function directly. That test needs no files and no I/O, and it is where most bugs in validation code are actually found. Integration tests then only need to confirm that the same function is called on real data and that the reject counters appear in the logs.

One failure mode deserves its own note: validation that logs and continues without limit. A corrupt file with a million bad lines will flood logs and slow the run to a crawl. Cap the number of detailed log lines per category (for example, the first ten, then a running count), and keep the full count in the summary.

Where validation stops and professional help begins

If a repeated parse failure points at a binary format mismatch — records arriving at shifted offsets, fields that look like plausible numbers but change every run — stop adjusting the validation rules and check the format definition, version, and endianness against the producer. Masking a structural mismatch with more lenient parsing turns a format bug into wrong data that passes all your checks, which is worse than an obvious rejection. The same stop condition applies when the source itself is changing (a feed whose fields change meaning between releases): the fix belongs in a documented versioning agreement, not in the parser.

Used this way, "disregarding incorrect values" is a small amount of code and a larger amount of written policy: one defined rule per field, one function that applies it, one counter per rejection reason, and a test table of the inputs most likely to break it. The values you keep are then exactly the ones you can defend.