Passing of values from text file to array

后端 未结 2 900
离开以前
离开以前 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: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.

提交回复
热议问题