Reading in Data From a File Into an Array C++

  1. #1

    kal123456 is offline

    Registered User


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

    Hey everyone!

    Then 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 print the values to the user. However, when I run the program, information technology merely outputs nothing to the user..just a blank infinite, i don't see any values.... i created the .txt file and saved it into "My Documents" on my computer then I'thousand pretty sure the program knows how to access information technology....peradventure there'south another fault in my code that i'thou non communicable?

    If anyone would like to assist, I would profoundly capeesh your help!!
    Give thanks You

    And here'due south my code:

    Code:

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


  2. #2

    nonpuz is offline

    Ultraviolence Connoisseur


    Other then the fact that:

    Lawmaking:

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

    Code:

    int nums[50] = {0};
    There is zilch wrong with the code and as long equally votes.txt is in the electric current directory the plan is run from, should piece of work fine. What are the contents of votes.txt?
    Should be something similar:

    Code:

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


  3. #3

    nonpuz is offline

    Ultraviolence Connoisseur


    Encounter, 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]);      render 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[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[6] = 437 num[5] = 402348 num[4] = 340823 num[3] = 3498 num[2] = 344908 num[ane] = 34 num[0] = 234
    You should actually throw a i < 50 check in the while () condition as well.
    Last edited by nonpuz; 01-xi-2013 at 11:59 PM. Reason: Pointed out the demand for bound checking in the while loop


  4. #iv

    kal123456 is offline

    Registered User


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

    Code:

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

    Lawmaking:

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

    OHHHH i simply saw your answer......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 see if it works at present!!!

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


  5. #5

    nonpuz is offline

    Ultraviolence Connoisseur


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

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

    Code:

    #include <stdio.h>  int main(void) {     int candidates[5] = {0};     int i;     FILE * fp;      /* note this has no l size limit every bit earlier.. */     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!\n", i);                 go on;             }              /* 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. #vi

    kal123456 is offline

    Registered User


    ok allow me encounter if the code that u gave me works...and it merely gives me the black running window with a bare space at where the values are supposed to be printed, and and so:

    "Process returned 0 (0x0) execution fourth dimension : 0.031 south
    Printing any key to go on."

    idk whats wrong!!

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


  7. #7

    nonpuz is offline

    Ultraviolence Connoisseur


    Read and Answer my questions, then maybe yous volition 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 work if the data file is moved or copied into the same directory that it is located in.

    Not "My Documents". Must exist the very aforementioned directory. You aren't seeing the error message, because the panel window is closing before you tin can see the message.

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


  9. #nine

    kal123456 is offline

    Registered User


    @nonpuz

    Ok and then you asked how I was executing information technology--I'yard using codeblocks, just building and running the program. Ok, and then I used the code yous just gave me (the candidate one) and it's finally outputting some results!!! Thank you!! The but problem is that I demand the upward to 50 size limit to all the same be there (because what if I take more than 50 numbers?), but i'll endeavor and figure that out on my own. Likewise, the output that i become is:

    Candidate #0 had 0 votes
    Candidate #1 had 0 votes
    Candidate #2 had 0 votes
    Candidate #3 had 0 votes
    Candidate #four had 0 votes
    Candidate #v had 0 votes
    Candidate #6 had 0 votes
    Candidate #7 had 0 votes
    Candidate #8 had 0 votes
    Candidate #ix had 0 votes

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

    In my example, in that location are simply 5 candidates, so ignore the output stuff for "candidate 5" to "candidate 9". Just look at the candidate vote count until "candidate 4". Somehow it says that all five candidates got 0 votes...how practice I get the program to really print out the number of votes each candidate has? please give me slight hints, I'll try to figure nigh of it out on my own, It wouldnt be off-white 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. #xi

    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 correct after the "fopen" phone call that simply says "openned file successfully". Execute and run and see if it outputs opened file successfully. If it does, then move on and put a printf() phone call in the while loop just earlier the ++candididate[i] line;


  12. #12

    Salem is offline

    and the lid of int overfl Salem's Avatar



barnerarnament.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel