gpt4 book ai didi

C 编程 : Storing and classifying strings into an array from a text file

转载 作者:行者123 更新时间:2023-11-30 20:22:20 25 4
gpt4 key购买 nike

基本上我想做的是从文本文件中读取微分方程,然后用撇号对它们进行分类(' 是一阶)('' 是二阶),然后将每个方程存储到一个数组中,我可以然后打印它们是否是一阶或二阶。它说我没有错误,但是当我运行它时,我的编译器崩溃了。我做错了什么?

#include <stdio.h>
main()
{
FILE *fin;
int i;
char line[300];
int value = 0;
fin = fopen("DIFFERNTIAL_EQNS.txt", "r");
while(fgets(line, sizeof line, fin) != EOF)
{
for (i = 0; i < 300; i++)
if (line[i] == ('\''))
{
if (line[i++] == ('\''))
{
value = 2;
}
value = 1;
}
}

if (value == 1)
printf("this is 1st order\n");
else
printf("this is 2nd order\n");

fclose(fin);
}

最佳答案

您的代码有几个问题:

我认为这一行有问题:

    while(fgets(line, sizeof line, fin) != EOF)

fgets 不返回 EOF。完成后(或出错时),它会返回 NULL

所以尝试一下:

    while(fgets(line, sizeof line, fin) != NULL)

或者只是

    while(fgets(line, sizeof line, fin))

此外,这条线很糟糕:

for (i = 0; i < 300; i++)

您无法确定 fgets 填充了整个行数组。相反,请执行以下操作:

for (i = 0; line[i]; i++)   // or for (i = 0; line[i] != '\0'; i++)

这样您只能继续直到零终止。

你这里有一个错误:

    if (line[i] == ('\''))
{
if (line[i++] == ('\'')) <---- use +1 instead
{
value = 2;
}
value = 1; // <------ You always overwrite with 1 so you never get 2
}

而是这样做:

    if (line[i] == ('\''))
{
value = 1;
if (line[i+1] == ('\''))
{
value = 2;
}
}

此外,您的代码似乎只能处理一行,因为您只是在每个循环中覆盖 value 。也许您想将打印内容放入循环内。喜欢:

while(fgets(line, sizeof line, fin))
{
for (i = 0; line[i]; i++)
if (line[i] == ('\''))
{
value = 1;
if (line[i+1] == ('\''))
{
value = 2;
}
}

// Print the result for this line before reading next line
if (value == 1)
printf("this is 1st order\n");
else if (value == 2)
printf("this is 2nd order\n");
else
printf("Didn't find anything\n");

value = 0;
}


fclose(fin);

然后另一个问题 - 考虑输入:

x'' + 3x' + x

上面的代码会说它是一阶,因为 3x' 会将值“覆盖”为 1。因此,您需要确保不会从 2 变回 1。也许像:

    if (line[i] == ('\''))
{
if (value == 0) value = 1; // Changed this
if (line[i+1] == ('\''))
{
value = 2;
}
}

关于C 编程 : Storing and classifying strings into an array from a text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39803907/

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