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

标签 c

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

#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/

相关文章:

可以延迟分配静态内存吗?

核心基础,CF PRIVATE 定义在哪里

c - 我不知道为什么会收到段错误错误

c - 如何将特定线程的标准输出重定向到/dev/null?

c - C 语言 TCP/IP 套接字中片段的说明

c++ - 使用 ReadFile() 简单读取文件

c - 为什么在写入使用字符串初始化的 "char *s"时会出现段错误,而不是 "char s[]"?

`printf` 语句里面的条件

c - 使用循环将输入输入到链表中

c - 使用 libpulse 播放多个流