简体   繁体   中英

Dealing with unexpected input

Just a small query really, through the use of scanf, which in my case, will be scanning in X number of integers into variables, each integer separated by a space. Any hints/clues as to how to deal with input if when the integers are input, there are no spaces between them, for example, my input is such XXXX, but if XX XX was input, how could I deal with that within my scanf function?

Bearing in mind my scanf(%d %d %d %d"....)

Cheers.

I would read one value at a time with a counter and check whether a number is larger than 9, 99 or 999 to check for multiple digits. If you do, extract each digit with division and increase your counter for each digit.

You could check the return value of your scanf() to make sure it matches, and then validate that the values are between 0 and 9 after you receive them. Like so:

int vars[4];
if (scanf("%d %d %d %d", vars[0], vars[1], vars[2], vars[3]) != 4) {
    // error
}

Then check each variable for being in range:

for (int i = 0; i < 4; i++) {
    if (vars[i] < 0 || vars[i] > 9) {
        // error
    }
}

I'd just avoid scanf() . If each integer is just a single digit, something like the following would probably work:

int vars[4];
for (int i = 0; i < 4;) {
  int c = getchar();
  if (isdigit(c)) {
    vars[i++] = c - '0';
  } else if (!isspace(c)) {
    // error
    break;
  }
}

The above does of course assume that the digits are '0' to '9' and have increasing, sequential values... and are each represented by a single char -- but those are probably safe assumptions.

While scanf reads after the enter button is pressed, it might be easier to read the line as a string and then try to analyze it. You can correct your input with backspace etc. on a fully featured terminal, so it's a bit more comfortable for user than getchar. We look for single digits only, is that right?

Maybe something like:

char buffer[SOMECOUNT];
int digits[4];
int read, i;
scanf("%s", buffer);
for(int i = 0; i < strnlen(buffer, SOMECOUNT); ++i)
{
    if( read >= 4 )
         break;
    if( isdigit(buffer[i]) )
    {
         digits[read] = buffer[i] - '0';
         read++;
    }
 }
if ( read < 4 )
    printf(error...);

Of course, this SOMECOUNT constant makes the solution a bit fragile for nasty input, so you may want to use the limit: scanf("%20s",buffer) or even construct the format string to include SOMECOUNT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM