Reading an Array From a File C++

  1. #1

    kal123456 is offline

    Registered User


    Exclamation reading from file and storing the values in an assortment!! Aid PLEASE!! :O

    Hey everyone!

    So i have a simple program that's supposed to read up to 50 values from a .txt file, store the values in an array, and impress the values to the user. Still, when I run the plan, information technology simply outputs aught to the user..merely a blank space, i don't run into any values.... i created the .txt file and saved it into "My Documents" on my computer and then I'one thousand pretty sure the program knows how to admission it....maybe in that location's some other mistake in my code that i'grand non catching?

    If anyone would like to help, I would greatly appreciate your help!!
    Thank You

    And here'due south my code:

    Code:

    /*Written by: Kalpana Chinnappan Appointment: January 17, 2013 Homework 1 */     #include <stdio.h>      int main (void)  {     int nums[l];   //upward to 50 element int array     FILE *fp1;      //file arrow     int i;      //******************  code starts here ***************     for(i=0;i<50;i++)   //initialize array with 0         nums[i]=0;     i=0;        //clean up and initialize LCV     if ((fp1=fopen("votes.txt","r"))==NULL)     {     printf("votes.txt failed to open\northward");     render 1;     }     else         while((fscanf(fp1,"%d",&nums[i]))!=EOF) //scanf and cheque EOF         {             printf("nums[%d] is %d\n",i,nums[i]);             i++;         }       return 0;  }


  2. #2

    nonpuz is offline

    Ultraviolence Connoisseur


    Other then the fact that:

    Code:

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

    Lawmaking:

    int nums[50] = {0};
    At that place is nothing wrong with the lawmaking 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:

    Lawmaking:

    $ 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; } $ true 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[fifteen] = 34987 num[14] = 38947 num[thirteen] = 9349873 num[12] = 28934 num[11] = 498724 num[x] = 348973 num[9] = 293847 num[8] = 43298 num[seven] = 43297 num[half-dozen] = 437 num[five] = 402348 num[4] = 340823 num[3] = 3498 num[2] = 344908 num[1] = 34 num[0] = 234
    Y'all should actually throw a i < fifty check in the while () condition likewise.
    Last edited by nonpuz; 01-11-2013 at 11:59 PM. Reason: Pointed out the demand for bound checking in the while loop


  4. #4

    kal123456 is offline

    Registered User


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

    Code:

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

    Lawmaking:

                                                      0 3 3 2 iii 0 4 two four iv 2 0 0 0 iv 2 3 3 3 3 0 2 0 0 1 1 1 2 iii 4 4 0 3 iv 0 0 3 3 iv 4 iv 4 0                                              

    OHHHH i just saw your answer......maybe that's my problem, cause I didn't include the i<fifty in my while loop....thanks soooo much for helping out!! lemme go and encounter if information technology works now!!!

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


  5. #5

    nonpuz is offline

    Ultraviolence Connoisseur


    Similar I said there is nothing in the code that is causing information technology to not work. How are y'all executing it? Is information technology simply running a quick popup window and and then disappears?

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

    Code:

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


  6. #6

    kal123456 is offline

    Registered User


    ok permit me see if the code that u gave me works...and information technology just gives me the black running window with a blank space at where the values are supposed to be printed, then:

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

    idk whats wrong!!

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


  7. #7

    nonpuz is offline

    Ultraviolence Connoisseur


    Read and ANSWER my questions, then perhaps yous volition figure it out ?


  8. #8

    Adak is offline

    Registered User


    Welcome to the forum, kal!

    Your file is non beingness opened. Your program will only work if the data file is moved or copied into the aforementioned directory that it is located in.

    Non "My Documents". Must be the very same directory. You lot aren't seeing the error message, considering the panel window is closing before you tin can see the message.

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


  9. #9

    kal123456 is offline

    Registered User


    @nonpuz

    Ok and so you asked how I was executing it--I'm using codeblocks, just building and running the plan. Ok, so I used the code you just gave me (the candidate 1) and it's finally outputting some results!!! Thanks!! The only problem is that I need the up to 50 size limit to still be there (because what if I have more than 50 numbers?), but i'll effort 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 #five had 0 votes
    Candidate #half-dozen had 0 votes
    Candidate #vii had 0 votes
    Candidate #viii had 0 votes
    Candidate #9 had 0 votes

    Procedure returned 0 (0x0) execution time : 0.031 southward
    Printing whatever key to proceed.

    In my case, in that location are just 5 candidates, then ignore the output stuff for "candidate 5" to "candidate ix". Just look at the candidate vote count until "candidate 4". Somehow it says that all five candidates got 0 votes...how exercise I become the program to actually print out the number of votes each candidate has? delight requite me slight hints, I'll attempt to figure almost of it out on my own, It wouldnt be fair if u did my homework for me haha :P


  10. #ten

    kal123456 is offline

    Registered User


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


  11. #11

    nonpuz is offline

    Ultraviolence Connoisseur


    Ok so that tells me that its non reading anything from your file. Either the file is not in the directory or it is non readable or fscanf is failing. Put a "printf()" call right after the "fopen" call that just says "openned file successfully". Execute and run and encounter if it outputs opened file successfully. If it does, then movement on and put a printf() phone call in the while loop simply before the ++candididate[i] line;


  12. #12

    Salem is offline

    and the lid of int overfl Salem's Avatar



bryantanch1974.blogspot.com

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

0 Response to "Reading an Array From a File C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel