简体   繁体   中英

How can I modify the c program such that if the user enters a non-float input,“invalid input” is shown to the user?

Here is the code:

// c program to add 10 elements entered by the user
#include <stdio.h>
int main()
{
    int i;
    float elements[10]; //declaring the array
    float sum = 0;

    for (i = 0; i < 10; ++i)
    {
        printf("Enter element %d: ", i + 1); //getting the elements from  the user
        scanf("%f", &elements[i]);           //storing the elements
        sum += elements[i];                  //adding integers entered by the user to t   he sum variable
    }

    printf("sum of above entered elements is : %.4f", sum); //printing the sum to four decimal places
    return 0;
}

Do something like:

  • Let the user input a string
  • Validate input on the string
  • Convert it to a float if everything is fine.

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