Home > Enterprise >  I want to take comma-separated integers and place them in an array that terminates with a question m
I want to take comma-separated integers and place them in an array that terminates with a question m

Time:11-15

C noob here. I'm trying to take in comma-separated integers and place them in an array that terminates with (and contains) a question mark. The input must have a comma and yet when I take the input it does not seem to require it. So far I have:

    char Array1[100];
    int i;
    do {
        scanf("%d,\n", &Array[i]) {
        i  ;
    } while (Array[i] != '?');
}

I guess I'm trying to say that I want to make the delimiter (,) necessary for every digit input (except the last which must end in a question mark) but scanf seems to be brushing right past that requirement.

CodePudding user response:

There are multiple problems in the code.

  • you do not check for array boundaries: entering more than 100 numbers followed by a comma would cause undefined behavior
  • testing Array[i] != '?' is wrong on many levels: the character after the number is not stored into the array, numbers are converted so testing for '?' means testing if the number happens to be 63, the ASCII code for ?, and the test uses the next entry in the array which content is uninitialized, invoking undefined behavior too.
  • a trailing \n in the scanf format string will cause scanf() to keep reading from the user until a non white space character is read after the , consuming and discarding and newlines.

You should use a simpler loop, reading both the number and the separator and test the separator explicitly:

    char Array[100];
    int i = 0;
    char c;
    while (i < 100) {
        if (scanf("%d%c", &Array[i], &c) != 2)
            break;
        i  ;
        if (c == ',')
            continue;
        if (c == '?')
            break;
        printf("invalid separator: %c\n", c);
        break;
    }
  • Related