0

I am writing a code and I need to use a loop. I am reading data from a file (data.txt) that looks like this:

IMPORT 450

EXPORT 200

IMPORT 100

and so on.

Here is the segment of the code that I am having trouble with

inputfile = fopen("c:\\class\\data.txt","r");
fscanf(inputfile,"%s %f", &transaction, &amount);

do{                 
     total += amount;             
     printf("Data %s  %f   %f\n", transaction, amount, total);
     fscanf(inputfile, "%s", &transaction);

}while (transaction == "IMPORT" || transaction == "EXPORT");

When I add a printf line to check what 'transaction' is it shows IMPORT, so I am not sure why the do-while loop is not repeating.

Thank you!

0

4 Answers 4

4

Assuming transaction is a char array, the comparison

transaction == "IMPORT"

will compare the address of transaction against the address of the string literal "IMPORT".

You need to use

while (strcmp(transaction, "IMPORT") == 0 ||
       strcmp(transaction, "EXPORT") == 0)

to compare strings in C.

Sign up to request clarification or add additional context in comments.

Comments

1

What type is transaction?

In order to use it with fscanf's %s operator it probably is char[], and in that case you need to use strcmp; the == operator will compare character pointer addresses, rather than contents.

Comments

0

When you try to check transaction == "IMPORT" C only compares the pointer of the first char. That doenst work really well. Maybe try this code:

int str_equal(char* str1, char* str2)
{
    int i, len;

    if ((len = strlen(str1)) != strlen(str2))
    {
        return 0;
    }

    for (i = 0; i < len; i++)
    {
        if (toupper(str1[i]) != toupper(str2[i]))
    {
            return 0;
        }
    }

    return 1;
}

Comments

0

probably like this

    while(2==fscanf(inputfile,"%s %f", transaction, &amount)){
        if(strcmp("IMPORT", transaction)==0)
            total += amount;
        else if(strcmp("EXPORT", transaction)==0)
            total -= amount;
        else
            break;
        printf("Data %s  %f   %f\n", transaction, amount, total);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.