If character then redo the function

前端 未结 2 986
醉话见心
醉话见心 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 
    #include 
    
    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;
    }
    

提交回复
热议问题