Stop a for loop when user is finished entering input in c

前端 未结 5 1428
梦如初夏
梦如初夏 2021-01-20 21:27

First of all, thank you for the assist!

I\'m new to the C language (and programming in general) and I\'m trying to write a program wherein the user inputs data point

5条回答
  •  孤街浪徒
    2021-01-20 21:37

    For your task the loop of gathering input should control not only keyword, but also number if inputs. I suggest to do this as follows:

    #include 
    #include 
    #define NUM_OF_DATA 1048
    
    int main(void) 
    {
        printf("\n Welcome! \n\n Please enter each data point. Enter 'done' when finished.\n\n");
        double data[NUM_OF_DATA];
        int i; // counter of entered numbers
        char str[5] = { 0 }; // string to read 'done' or other word from input
        for (i = 0; i < NUM_OF_DATA; i++) // the first index of data in array is 0 (the last NUM_OF_DATA-1)
        {
            printf("Data[%i]: ", i);
            if (1 == scanf("%lf", &data[i])) // if number was successfully read
                continue; // go to next iteration
            // if some problem was with reading a loat number
            // read the string
            scanf("%4s", str); // read not more than 4 characters from input
            if ( strcmp(str, "done") == 0) 
            {
                break; // stop input if 'done' was entered
            }
            // clean input buffer before next input
            while (getchar() != '\n');
            // correct counter in case of wrong input
            i--;
        }
        // output the number of correct inputs
        printf("%d numbers were entered.\n", i);
        // do something with data
        // taking in account, that i is not index of the last element, 
        // but the number of elements (indexes are 0 ... i-1)
        // ...
        return 0;
    }
    

    This for loop stops in two cases:

    1) when data array is full,

    2) when 'done' without quotes entered.

    Additional feature is skipping of incorrect input (try how it works).

提交回复
热议问题