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

前端 未结 5 1423
梦如初夏
梦如初夏 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:55

    Bottom line: don't use scanf.

    Use something like

    char inputline[100];
    
    i = 0;
    
    while(fgets(inputline, sizeof(inputline), stdin) != NULL) {
        if(strncmp(inputline, "done", 4) == 0) break;
        data[i++] = atof(inputline);
    }
    

    scanf is hard enough to use even when all your inputs are the numbers you expect. If the input might be either a number or the word "done", scanf will never work. But reading a line of text, as here, is generally easier and more flexible.

    P.S. You also have to worry about the possibility that the user enters more than 1048 numbers.

提交回复
热议问题