If character then redo the function

前端 未结 2 954
醉话见心
醉话见心 2021-01-28 13:30

In C code. This is the part I want to work on below. I want to be able to do... if a character value then say \"not a number\", however, because it is an array and it increments

相关标签:
2条回答
  • 2021-01-28 14:34

    Some help to get you started, scanf returns the number of successfully read items (matching % marks in format string). So you can evaluate this number and take action accordingly.

    int n=scanf("%f", &sal[i]);  
    if (n !=1){
      // do something here 
    }
    

    Hint: There is a common problem with using scanf,in that it wont recover from a "bad" input, unless you empty the buffer by "eating" the bad string.

    If you want to convince your teacher that you have a VERY BIG BRAIN /s, you could do something like this;

    #include <stdio.h>
    #include <string.h>
    
    void getSalaries (float sal[], int size)
    {
    
      char *scan_fmt[2] = {
        "%f",           // Get float
        "%*s%f"         // Eat previous bad input, and get float
      };
      char *cli_mess[2] = {
        "Enter salary for Employee #%d: ",
        "Try again, for Employee #%d: "
      };
    
    
      for (int i = 0, n=1; i < size; i += n==1){
          printf (cli_mess[n!=1], i + 1);
          n = scanf (scan_fmt[n!=1], &sal[i]);
      }
    }
    
    
    int main ()
    {
      float s[3];
      getSalaries (s, 3);
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-28 14:37

    If you want to repeat something, you need a loop. If you don't know how many times you'll want to loop in advance, it's probably going to be a while loop. The following structure will achieve your goal cleanly:

    while (1) {
       printf("Enter salary for Employee #%d: ", i + 1);
       scanf("%f", &sal[i]);        
       if (...valid...)
          break;
    
       printf("Not a Number. Try again.\n");
    }
    

    The value returned by scanf will help you determine if the input was valid. I will leave consulting the documentation and finishing that part of your homework to you.

    0 讨论(0)
提交回复
热议问题