0

I am reading data from a file and writing it into an array. This works but I can't seem to read it back out of the array properly. Where is the mistake?

int main(){

    struct mountain{
        char name[300];
        char height[5];
    };

    struct mountain mountainArray[8];

    fp = fopen("berge.txt", "r");

    if(fp == NULL) {
        perror("Error opening file");
        return(-1);
    }

    int i=0;
    while ( fgets(readLine, buflen, fp)){
        if(i<8){

            char * p;

            p = strtok (readLine,":");
            if (p != NULL){

                strcpy(mountainArray[i].name,p);
                p = strtok (NULL, ":");
                if (p != NULL)
                    strcpy(mountainArray[i].height,p);
            }

            i++;

        }
    }

    unsigned int f;
    for (f=0; f<8; f++){

        printf("%s\n", mountainArray[i].name);
    }
    fclose(fp);

    return 0;
}

2 Answers 2

2

in line

printf("%c\n", mountainArray[i].name);

I think you mean f for the index, not i.

(and Ivaylo is right - you want %s for strings.)

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

2 Comments

That did it how embarassing!
Please handle error conditions as well in the program @HansEn by using setting NULL value for structure members, else in for loop it would print out junk for rest of members.
0

You should print a string using %s format specifier not %c.

1 Comment

Yeah. That prints me p@ every line. If I debug, I can see that the array is filled with data. I just can´t seem to read it back out.

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.