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 out to an output file.
Example input file:
red, green, blue
green, gray, yellow
Example output file:
Resistance in ohms = 680
Resistance in kilo-ohms = 1420
However, every time I run the program it crashes. I've done some debugging and found that it has a problem with the yellow index from decodeString function giving it a NULL value. I've partially fixed that problem by passing the values to the function decodeString instead of using pointers and now it seems to work.
Right now I don't get the correct output that I'm expecting and I don't know where the error is coming from. The code I have runs, but doesn't give the correct output at the moment. I just don't know where to look anymore.
Think anyone can help me fix this? Or if there's anything that I might have done wrong please point it out and explain why it went wrong. That'll be greatly appreciated!
The commented lines were used for debugging.
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define size 100
int DecodeString(char inputString[]){
const char kColorTable[10][10] = {"black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "gray", "white"};
int i;
for(i=0; i<10; i++){
//printf("\n>>%s,%s",inputString,kColorTable[i]);
if(strcmp(inputString, kColorTable[i]) == 0){
return i;
}
}
return -1;
}
int main(){
int i=0, colord[3]={0,0,0};
char color[size], *token, *inputString;
double resistance=0, value;
FILE *fptrin, *fptrout;
if(((fptrin = fopen("input.txt", "r"))==NULL) || ((fptrout = fopen("output.txt", "w")) == NULL)){
printf("Error 404: File not found");
exit(1);
}
while(fgets(color, size, fptrin)!=NULL){
token = strtok(color, ",");
while(token != NULL){
if(token[strlen(token)-1]=='\n')
token[strlen(token)-1]='\0';
colord[i] = DecodeString(token);
//printf(">>%s:%d ",token,colord[i]);
i++;
token = strtok(NULL, ",");
puts("");
}
//printf("<><>");
if (colord[0] == -1 || colord[1] == -1 || colord[2] == -1){
printf("\n\nBad code -- cannot compute resistance\n");
}
else{
resistance = (10.0 * colord[0] + colord[1]) * pow(10.0, colord[2]);
}
printf("%f",resistance);
if(resistance > 1000){
fprintf(fptrout,"Resistance in Kilo-Ohms: %f",resistance);
}
else{
fprintf(fptrout,"Resistance in Ohms: %f",resistance);
}
}
//fclose(fptrin);
//fclose(fptrout);
getchar();
return 0;
}
So I tried to debug my program to find out what's going on and this is the result that I get.
blue,black
blue,brown
blue,red
blue,orange
blue,yellow
blue,green
blue,blue
red,black
red,brown
red,red
,blackn
,brownn
,redown
,orange
,yellow
,greenn
,bluewn
,violet
,graywn
,whiten
file not foundis going to cause confusion when the issue is lack of permission. Tryif(fopen(path, "r") == NULL { perror(path) ...strtok(color, ",\n");andstrtok(NULL, ",\n");colord[i]will break the array. Best to limiti.