Pogo947
Pogo947

Reputation: 1

Program Crash when Reading from File

#include <stdio.h>
#include <string.h>

struct candidate
{
char candidateName[20];
int votes;
};



Initialize()
{
    char firstname[10];
    char lastname[10];
    FILE* ifp;
    int i;
    struct candidate electionCandidates[7];
    ifp = fopen("elections.txt", "r");
    for (i = 0; i<7; i++)
    {
        strcpy(electionCandidates[i].candidateName, "aaaaa");
        electionCandidates[i].votes = 0;
    }
    for (i=0; i<7; i++)
    {
        memset(&firstname[0], 0, sizeof(firstname));
        memset(&lastname[0], 0, sizeof(firstname));

        fscanf(ifp, "%s %s", &firstname, &lastname);
        strcat (firstname, " ");
        strcat (firstname, lastname);
        strcpy (electionCandidates[i].candidateName, firstname);
        printf("%s", electionCandidates[i].candidateName);
    }


}

int main()
{
    Initialize();
    return(0);
}

The above code is supposed to read first and last names from a file, and add them to the candidateName portion of the struct. When I run this program, it assigns and prints the begginning first and last name, but then immediately crashes.

The file is in the format of

first last

first last

first last

etc

I feel like this may have something to do with it not going to read the next line, but I do not know how to do so. Any help would be greatly appreciated.

Upvotes: 0

Views: 62

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Problems I see:

Problem 1

The line:

fscanf(ifp, "%s %s", &firstname, &lastname);

is a problem if the first name and/or the last name in the input file is longer than 9 characters.

To take care of that problem, specify the maximum number of characters you want to read. Also, from a type point of view, use firstname instead of &firstname.

fscanf(ifp, "%9s %9s", firstname, lastname);

Problem 2

The lines

strcat (firstname, " ");
strcat (firstname, lastname);

is a problem if length of firstname + length of lastname is greater than 8.

You can use:

strcpy (electionCandidates[i].candidateName, firstname);
strcat (electionCandidates[i].candidateName, " ");
strcat (electionCandidates[i].candidateName, lastname);

to solve that problem.

Upvotes: 1

Related Questions