Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read a Text File Into an Array C++

  1. #1

    kal123456 is offline

    Registered User


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

    Hey everyone!

    So i have a unproblematic plan that's supposed to read upwards to fifty values from a .txt file, store the values in an array, and print the values to the user. Still, when I run the program, it just outputs nothing to the user..just a blank space, i don't see whatever values.... i created the .txt file and saved it into "My Documents" on my computer and then I'g pretty sure the program knows how to access it....maybe there's another mistake in my lawmaking that i'grand not catching?

    If anyone would similar to help, I would greatly capeesh your help!!
    Thank You

    And here's my code:

    Code:

    /*Written by: Kalpana Chinnappan Date: January 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<50;i++)   //initialize assortment with 0         nums[i]=0;     i=0;        //clean upward and initialize LCV     if ((fp1=fopen("votes.txt","r"))==Zilch)     {     printf("votes.txt failed to open\n");     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++;         }       render 0;  }


  2. #ii

    nonpuz is offline

    Ultraviolence Connoisseur


    Other and then the fact that:

    Lawmaking:

                          //******************  code starts here ***************     for(i=0;i<l;i++)   //initialize assortment with 0         nums[i]=0;
    Tin can easily be done at initialization:

    Code:

    int nums[50] = {0};
    In that location is zero wrong with the code and as long every bit votes.txt is in the current directory the program is run from, should work fine. What are the contents of votes.txt?
    Should exist 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 main(void) {     int nums[50] = {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\n", 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[eighteen] = 48 num[17] = 293847347 num[16] = 293847 num[15] = 34987 num[14] = 38947 num[thirteen] = 9349873 num[12] = 28934 num[11] = 498724 num[ten] = 348973 num[9] = 293847 num[8] = 43298 num[7] = 43297 num[half-dozen] = 437 num[5] = 402348 num[4] = 340823 num[3] = 3498 num[2] = 344908 num[i] = 34 num[0] = 234
    You should really throw a i < l cheque in the while () condition besides.
    Last edited by nonpuz; 01-11-2013 at 11:59 PM. Reason: Pointed out the need for jump checking in the while loop


  4. #4

    kal123456 is offline

    Registered User


    Ohh ok, so I can just replace that whole "for" loop with:

    Code:

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

    Lawmaking:

                                                      0 3 three 2 3 0 4 2 4 4 2 0 0 0 4 ii 3 iii 3 3 0 2 0 0 1 1 1 2 iii 4 four 0 three four 0 0 3 3 4 4 4 4 0                                              

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

    Last edited by kal123456; 01-12-2013 at 12:06 AM.


  5. #5

    nonpuz is offline

    Ultraviolence Connoisseur


    Like I said there is zilch in the code that is causing it to not work. How are you executing it? Is it just running a quick popup window and so disappears?

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

    Lawmaking:

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


  6. #half-dozen

    kal123456 is offline

    Registered User


    ok permit me see if the code that u gave me works...and it merely gives me the black running window with a blank space at where the values are supposed to exist printed, and so:

    "Process returned 0 (0x0) execution time : 0.031 s
    Printing any key to go on."

    idk whats wrong!!

    Last edited by kal123456; 01-12-2013 at 12:18 AM.


  7. #7

    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 non being opened. Your program will but work if the information file is moved or copied into the same directory that it is located in.

    Not "My Documents". Must be the very same directory. You aren't seeing the fault message, because the console window is closing earlier you lot can see the bulletin.

    Concluding 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 lawmaking you only gave me (the candidate 1) and it'due south finally outputting some results!!! Give thanks you lot!! The simply problem is that I need the upwards to 50 size limit to still be at that place (because what if I have more than than l numbers?), but i'll try and figure that out on my own. Also, the output that i go is:

    Candidate #0 had 0 votes
    Candidate #i had 0 votes
    Candidate #two had 0 votes
    Candidate #3 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 #nine had 0 votes

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

    In my example, there are only 5 candidates, so ignore the output stuff for "candidate 5" to "candidate 9". Just look at the candidate vote count until "candidate iv". Somehow it says that all five candidates got 0 votes...how do I get the program to actually print out the number of votes each candidate has? delight give me slight hints, I'll try to effigy most of information technology out on my own, It wouldnt be 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 non in the directory or it is non readable or fscanf is failing. Put a "printf()" telephone call correct after the "fopen" call that just says "openned file successfully". Execute and run and run into if information technology outputs opened file successfully. If it does, then motion on and put a printf() call in the while loop just before the ++candididate[i] line;


  12. #12

    Salem is offline

    and the lid of int overfl Salem's Avatar



schawnoweli.blogspot.com

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