Jacob Nelson
Jacob Nelson

Reputation: 3016

Checking what the input is like then using scanf (C)

So the issue is the user can either give input that is one int, or the user can give an input with three int. And it all depends on the first input. Little confusing so here is an example:

printf("Please enter input in this format: (-blackwhite | -color) colorvalue");

user inputs "-blackwhite 40" so I want to

scanf("%s %u", charArray, &int);

but user can also input "-color 254 254 254" then I would want to

scanf("%s %u %u %u", charArray, &int1, &int2, &int3);

How do I go about doing this? Basically verifying the data before I scan it into variables.

Upvotes: 1

Views: 386

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 754790

Read the string; compare the string with -blackwhite and read a single int if it matches; else compare the string with -color and read three ints if it matches; else bitch at the user.

if (scanf("%40s", charArray) == 1)
{
    if (strcmp(charArray, "-blackwhite") == 0)
    {
        if (scanf("%d", &int1) == 1)
            ...OK...
        else
            ...error...
    }
    else if (strcmp(charArray, "-color") == 0)
    {
        if (scanf("%d %d %d", &int1, &int2, &int3) == 3)
            ...OK...
        else
            ...error...
    }
    else
        ...error...

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 882336

Never use a naked (unbounded) %s in scanf unless you control totally the input data format (which you don't here).

Otherwise you open up your code to buffer overruns.

What you should do is to fgets a line from stdin (since this provides buffer overrun protection) then simply sscanf the line.

This has the added bonus that you can sscanf your longer four-argument format string and, if it fails, then try the two-argument one.

Something like this:

#include <stdio.h>

int main (void) {
    char buffer[200];
    int i1, i2, i3, count;

    printf("Please enter input in format: (-blackwhite | -color) colorvalue: ");
    fflush (stdout);
    if (fgets (buffer, sizeof (buffer), stdin) != NULL) {
        if ((count = sscanf (buffer, " -color %d %d %d", &i1, &i2, &i3)) != 3)
            count = sscanf (buffer, " -blackwhite %d", &i1);
        switch (count) {
            case  1: printf ("blackwhite %d\n", i1);          break;
            case  3: printf ("color %d %d %d\n", i1, i2, i3); break;
            default: printf ("Huh?: %s\n", buffer);           break;
        }
    }
    return 0;
}

Upvotes: 6

YeenFei
YeenFei

Reputation: 3218

if your parameter always start with "string input" then followed by N x "integer input", you can write your code using maximum possible number of integer input, as scanf will return you number of parameter filled.

Upvotes: 0

Alexander Rafferty
Alexander Rafferty

Reputation: 6233

Perhaps you should scan for the words first, test it, then scan for the numbers appropriately.

Upvotes: 1

Related Questions