[英]Passing of values from text file to array
我的代碼有問題。
我的程序根據來自輸入文件的三個波段的顏色計算電阻值,然后打印到輸出文件。
輸入文件示例:
紅色,綠色,藍色
綠色,灰色,黃色
輸出文件示例:
歐姆電阻= 680
千歐電阻= 1420
但是,每次我運行程序時,它都會崩潰。 我已經進行了一些調試,發現它來自decodeString
函數的yellow
索引有一個NULL
值,這是一個問題。 我已經通過將值傳遞給函數decodeString
而不是使用指針來部分解決了該問題,現在它似乎可以工作了。
現在,我沒有得到期望的正確輸出,也不知道錯誤從何而來。 我運行的代碼正在運行,但目前無法提供正確的輸出。 我只是不知道在哪里看了。
認為有人可以幫助我解決此問題嗎? 或者,如果有任何我可能做錯的事情,請指出並解釋為什么出錯。 這將不勝感激!
注釋行用於調試。
#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;
}
因此,我嘗試調試程序以了解發生了什么,這就是我得到的結果。
藍黑
藍色,棕色
藍紅
藍色,橙色
藍色,黃色
藍綠
藍色,藍色
紅黑
棕紅色
紅色,紅色
,黑色
,棕色
,redown
,橙子
,黃色
,格林
,bluewn
,紫色
,灰色
,變白
我看到的代碼中的第一個錯誤是您沒有從輸入字符串中刪除空格,這可以通過將標記分隔符字符串更改為" ,"
。 您也可以通過同時刪除換行符來簡化代碼。
限制i
的范圍也是謹慎的做法,因為任何多於3種顏色的行都會破壞colord[]
數組,這將引起您對第二個錯誤的注意,即您忘記在循環中重置i
了,並且這可以解釋為什么您會崩潰。
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
}
}
最后,在顯示千歐姆時應除以1000。
使用時
token = strtok(color, ",");
您只分割了“,”,但在文件后還有一個空格,因此它應該是
token = strtok(color, ", ");
或從文件中刪除空格
同樣對於千歐姆,我認為您在打印中忘了/ 1000
if(resistance > 1000){
fprintf(fptrout,"Resistance in Kilo-Ohms: %f",resistance/1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.