Passing of values from text file to array

后端 未结 2 878
离开以前
离开以前 2021-01-28 01:44

I\'m having some problems with my code.

My program calculates the amount of resistance based on the color of the three bands coming from an input file, then printing

相关标签:
2条回答
  • 2021-01-28 02:15

    When you use

    token = strtok(color, ",");
    

    you only split on "," but on the file you have also a space after it so it should probably be

    token = strtok(color, ", ");
    

    or remove the spaces from the file

    Also for the kilo-ohms i think you forgot a /1000 in the print

    if(resistance > 1000){
      fprintf(fptrout,"Resistance in Kilo-Ohms: %f",resistance/1000);
    }
    
    0 讨论(0)
  • 2021-01-28 02:33

    The first mistake in the code I see is that you are not removing the spaces from the input string, which you can do by changing the token separator string to " ,". You could also simplify the code a bit by removing the newline at the same time.

    It is also prudent to limit the range of i since any line with more than 3 colours will break the array colord[], and this would have drawn your attention to the second mistake, which is you forgot to reset i within the loop, and this could explain why you are getting crashes.

    while(fgets(color, size, fptrin) != NULL) {
        i = 0;                                  // reset `i`
        token = strtok(color, " ,\n");          // test for space and newline
        while(token != NULL && i < 3) {         // test `i` too
            colord[i] = DecodeString(token);
            i++;
            token = strtok(NULL, " ,\n");       // test for space and newline
        }
    }
    

    Finally you should divide by 1000 when displaying kOhms.

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