In the code snippet:

int Z;
boolean ParsedOk;
ParsedOk = sscanf( CommandLine, "%i", &Z ) == 1;

I find that a successful parse occurs for both valid numbers, but also for numbers that have trailing rubbish, such as '3Q', etc.

How can I detect (and reject) such malformed numerical input?

Recommended Answers

All 3 Replies

In the code snippet:

int Z;
boolean ParsedOk;
ParsedOk = sscanf( CommandLine, "%i", &Z ) == 1;

[...]
How can I detect (and reject) such malformed numerical input?

Check for trailing input as well.

if (sscanf(CommandLine, "%d%c", &Z, &ch) == 2 && (ch == '\n' || ch == '\0')) { 
    /* We got a winner */
} else {
    /* Anything else is uncivilized */
}

Hmm. thanks for that - kind of obvious, I guess! Now adapted to my actual needs and incorporated where required.

Hmm. thanks for that - kind of obvious, I guess! Now adapted to my actual needs and incorporated where required.

Yes, it needs adaptation. I left the part where it deals with spaces for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.