nicole panda nicole panda - 2 months ago 8
C Question

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

Basically what I'm trying to do is read differential equations from a text file, then classifying them by the apostrophes (' is first order) ('' is second order) and then storing each equation into an array which I can then print if they are first or 2nd order. It says I have no errors but when I run it, my compiler crashes. what did I do wrong?

#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);
}

Answer

Your code has several problems:

I think this line is a problem:

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

fgets doesn't return EOF. It returns a NULL when done (or on error).

So try:

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

or just

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

Further, this line is bad:

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

You can't be sure that fgets filled the whole line array. Instead do:

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

so that you only continue until the zero-termination.

The you have a bug here:

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

Instead do:

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

Also it seems your code can only handle one line as you just overwrite value in each loop. Maybe you want to put the print inside the loop. Like:

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);

Then another problem - consider the input:

x'' + 3x' + x

The code above will say it is 1st order because the 3x' will "overwrite" value to 1. So you need to make sure not go from 2 back to one. Maybe like:

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