gpt4 book ai didi

c - 将值从文本文件传递到数组

转载 作者:行者123 更新时间:2023-11-30 15:02:17 24 4
gpt4 key购买 nike

我的代码遇到一些问题。

我的程序根据来自输入文件的三个带的颜色计算电阻值,然后打印到输出文件。

输入文件示例:

red, green, blue
green, gray, yellow

示例输出文件:

Resistance in ohms = 680
Resistance in kilo-ohms = 1420

但是,每次我运行该程序时它都会崩溃。我做了一些调试,发现yellow有问题。索引来自decodeString函数给它一个 NULL值(value)。我通过将值传递给函数 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;
}

所以我尝试调试我的程序以了解发生了什么,这就是我得到的结果。

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

最佳答案

我看到的代码中的第一个错误是您没有从输入字符串中删除空格,您可以通过将标记分隔符字符串更改为 "," 来实现这一点。您还可以通过同时删除换行符来稍微简化代码。

限制 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
}
}

最后,在显示 kOhms 时应除以 1000。

关于c - 将值从文本文件传递到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41102475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com