Reputation: 520
I have a homework assignment that I am working on that deals with an array of structs. Basically I have to read data from a text file (elections.txt) that looks like this and then write these names into an array of structs for names:
Robert Bloom
John Brown
Michelle Dawn
Michael Hall
Sean O’Rielly
Arthur Smith
Carl White
The code I have written so far looks like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
FILE * data;
typedef struct
{
int votes;
char name[20];
}candidates;
void initialize( candidates *electionCandidates, FILE *data )
{
int i;
for( i=0; i<7; i++ );
{
fscanf( data, "%[^\n]%*c", electionCandidates[i].name );
printf( "%s\n", electionCandidates[i].name );
}
}
int processVotes( int p1, int p2 )
{
}
void printResults( int p1, int p2 )
{
}
int main() {
data = fopen( "elections.txt","r" );
candidates electionCandidates[7];
initialize( electionCandidates, data );
fclose( data );
return 0;
}
My problem is that when I run this program, what is printed on the screen is only the first name instead of all the names. I don't understand why this could be because I am looping through 7 positions of my struct array in the function. Can anyone point me in the right direction?
Upvotes: 0
Views: 94
Reputation: 2122
LOL even I broke my head over this and I realised this is a very silly mistake
for( i=0; i<7; i++ ); //<- Semicolon hiding like a boss.
This semi-colon causes the for loop to be empty hence you are just running an empty for loop 7 times and then reading electionCandidates[7].name and printing it.Just change it to :
int i;
for( i=0; i<7; i++ ){
fscanf( data, "%[^\n]%*c", electionCandidates[i].name );
printf( "%s\n", electionCandidates[i].name );
}
Upvotes: 2