How to Read a File and Put the Data Into an Array in C

  1. #1

    kal123456 is offline

    Registered User


    Exclamation reading from file and storing the values in an array!! HELP PLEASE!! :O

    Hey everyone!

    And then i have a elementary program that's supposed to read upwardly to fifty values from a .txt file, shop the values in an array, and impress the values to the user. However, when I run the programme, it just outputs aught to the user..just a blank space, i don't see whatsoever values.... i created the .txt file and saved information technology into "My Documents" on my computer and then I'm pretty sure the plan knows how to access information technology....possibly there'southward another mistake in my code that i'm not communicable?

    If anyone would like to aid, I would profoundly capeesh your help!!
    Thank you

    And here's my lawmaking:

    Code:

    /*Written by: Kalpana Chinnappan Date: Jan 17, 2013 Homework i */     #include <stdio.h>      int main (void)  {     int nums[50];   //up to 50 chemical element int array     FILE *fp1;      //file pointer     int i;      //******************  code starts here ***************     for(i=0;i<fifty;i++)   //initialize array with 0         nums[i]=0;     i=0;        //clean upwards and initialize LCV     if ((fp1=fopen("votes.txt","r"))==Null)     {     printf("votes.txt failed to open\north");     return i;     }     else         while((fscanf(fp1,"%d",&nums[i]))!=EOF) //scanf and bank check EOF         {             printf("nums[%d] is %d\n",i,nums[i]);             i++;         }       return 0;  }


  2. #two

    nonpuz is offline

    Ultraviolence Connoisseur


    Other then the fact that:

    Code:

                          //******************  lawmaking starts here ***************     for(i=0;i<l;i++)   //initialize array with 0         nums[i]=0;
    Tin hands be done at initialization:

    Code:

    int nums[50] = {0};
    In that location is aught wrong with the code and as long as votes.txt is in the current directory the program is run from, should work fine. What are the contents of votes.txt?
    Should be something like:

    Code:

    230 2398 34988 30489 9488 8598 34893 48984 34989 489 49848 58958 985


  3. #3

    nonpuz is offline

    Ultraviolence Connoisseur


    See, working fine for me:

    Code:

    $ cat test.c #include <stdio.h>    int master(void) {     int nums[fifty] = {0};     int i = 0;     FILE * fp;      if (fp = fopen("votes.txt", "r")) {         while (fscanf(fp, "%d", &nums[i]) != EOF) {             ++i;         }         fclose(fp);     }      for (--i; i >= 0; --i)         printf("num[%d] = %d\northward", i, nums[i]);      return 0; } $ cat votes.txt  234 34 344908 3498 340823 402348 437 43297 43298 293847 348973 498724 28934  9349873 38947 34987 293847 293847347 48 $ ./a.out  num[18] = 48 num[17] = 293847347 num[16] = 293847 num[xv] = 34987 num[14] = 38947 num[13] = 9349873 num[12] = 28934 num[11] = 498724 num[x] = 348973 num[9] = 293847 num[viii] = 43298 num[7] = 43297 num[half dozen] = 437 num[v] = 402348 num[four] = 340823 num[3] = 3498 num[2] = 344908 num[1] = 34 num[0] = 234
    Y'all should really throw a i < 50 check in the while () condition as well.
    Last edited by nonpuz; 01-11-2013 at xi:59 PM. Reason: Pointed out the need for leap checking in the while loop


  4. #four

    kal123456 is offline

    Registered User


    Ohh ok, so I tin but supersede that whole "for" loop with:

    Lawmaking:

                              int nums[50] = {0};
    I dont know if i'll practice it, but it should work both means, thanks for showing me a simpler way
    and actually, the contents are:

    Lawmaking:

                                                      0 iii three two 3 0 iv 2 4 4 ii 0 0 0 4 two three iii 3 three 0 2 0 0 1 one 1 2 three four 4 0 three 4 0 0 3 3 4 four four iv 0                                              

    OHHHH i just saw your reply......perchance that's my problem, cause I didn't include the i<l in my while loop....cheers soooo much for helping out!! lemme go and run into if it works now!!!

    Terminal edited past kal123456; 01-12-2013 at 12:06 AM.


  5. #5

    nonpuz is offline

    Ultraviolence Connoisseur


    Like I said in that location is nothing in the lawmaking that is causing it to not work. How are you executing information technology? Is it but running a quick popup window then disappears?

    Regarding your logic, if each numerical value represents a candidate then why not do something like this:

    Lawmaking:

    #include <stdio.h>  int main(void) {     int candidates[5] = {0};     int i;     FILE * fp;      /* note this has no 50 size limit as before.. */     if (fp = fopen("votes.txt", "r")) {         while (fscanf(fp, "%d", &i) != EOF) {             /* invalid vote (out of range */             if (i < 0 || i > five) {                 fprintf(stderr, "Invalid Candidate: %d!\northward", i);                 continue;             }              /* otherwise we got a valid vote, count information technology */             ++candidates[i];         }         fclose(fp);     }      for (i = 0; i < five; ++i)          printf("Candidate #%d had %d votes\n", i, candidates[i]);      return 0; }


  6. #6

    kal123456 is offline

    Registered User


    ok allow me meet if the code that u gave me works...and it simply gives me the blackness running window with a blank space at where the values are supposed to be printed, and and then:

    "Process returned 0 (0x0) execution time : 0.031 s
    Press any key to continue."

    idk whats wrong!!

    Last edited past kal123456; 01-12-2013 at 12:eighteen AM.


  7. #seven

    nonpuz is offline

    Ultraviolence Connoisseur


    Read and Answer my questions, then maybe yous will figure it out ?


  8. #8

    Adak is offline

    Registered User


    Welcome to the forum, kal!

    Your file is not being opened. Your program will only piece of work if the information file is moved or copied into the same directory that information technology is located in.

    Non "My Documents". Must be the very same directory. You aren't seeing the error message, because the console window is endmost before y'all can see the bulletin.

    Last edited by Adak; 01-12-2013 at 12:30 AM.


  9. #9

    kal123456 is offline

    Registered User


    @nonpuz

    Ok so you asked how I was executing it--I'm using codeblocks, just building and running the program. Ok, so I used the code you just gave me (the candidate ane) and information technology'due south finally outputting some results!!! Thanks!! The only problem is that I need the upward to 50 size limit to nonetheless exist there (because what if I have more than l numbers?), but i'll try and effigy that out on my own. Also, the output that i get is:

    Candidate #0 had 0 votes
    Candidate #1 had 0 votes
    Candidate #two had 0 votes
    Candidate #iii had 0 votes
    Candidate #4 had 0 votes
    Candidate #5 had 0 votes
    Candidate #6 had 0 votes
    Candidate #7 had 0 votes
    Candidate #8 had 0 votes
    Candidate #9 had 0 votes

    Process returned 0 (0x0) execution fourth dimension : 0.031 s
    Printing whatsoever key to keep.

    In my case, there are only v candidates, and so ignore the output stuff for "candidate 5" to "candidate nine". Simply await at the candidate vote count until "candidate 4". Somehow it says that all 5 candidates got 0 votes...how do I become the program to actually impress out the number of votes each candidate has? delight requite me slight hints, I'll try to figure most of it out on my own, Information technology wouldnt exist fair if u did my homework for me haha :P


  10. #10

    kal123456 is offline

    Registered User


    @Adak
    Ohhhhh!! Wow cant imagine why I couldnt figure that out earlier haha! Thanks!!


  11. #11

    nonpuz is offline

    Ultraviolence Connoisseur


    Ok then that tells me that its not reading anything from your file. Either the file is not in the directory or information technology is not readable or fscanf is declining. Put a "printf()" call right afterwards the "fopen" call that simply says "openned file successfully". Execute and run and see if it outputs opened file successfully. If it does, and then move on and put a printf() call in the while loop simply earlier the ++candididate[i] line;


  12. #12

    Salem is offline

    and the hat of int overfl Salem's Avatar



hallsawassin1951.blogspot.com

Source: https://cboard.cprogramming.com/c-programming/153674-reading-file-storing-values-array-help-please-o.html

0 Response to "How to Read a File and Put the Data Into an Array in C"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel