0

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?

6
  • 1
    I just saw a similar program but the question was diff. Same school I guess. Commented Sep 4, 2014 at 21:17
  • Yea its computer science at ucf. The program is called 'The Election' Commented Sep 4, 2014 at 21:20
  • 9
    for( i=0; i<7; i++ ); : remove ; Commented Sep 4, 2014 at 21:27
  • If I remove that then how can I put the names into the 7 different positions of my structure array? Commented Sep 4, 2014 at 21:31
  • 2
    @user3498869 look to the right of the word "remove" in that comment. See the ; ? the semi-colon after the ')' should not be there. Commented Sep 4, 2014 at 21:31

1 Answer 1

2

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 );
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wish I could upvote this but I don't have enough rep. You are EXACTLY right sir. Thank you so much.

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.