Good Morning DaniWeb users,

This will be the first time I use your forum to try and solve a problem.

I'm an non-traditional student and live in Michigan. For those curious about where that is located; look a world map (for our international friends) and look for the United States, my state looks like a hand.

I am in my first semester of C++ programming and my focus for my bachelors will be software engineering.

I have a program that I am having trouble, which, I am hoping is trivial to some of the more experienced memebers.

I have to declare a 500 element array. Get an unknown number of integers from a text file.

I have no trouble getting data from a text file when I know the amount of data that will be going into the array. However, when it is unknown I get some crazy results.

I have attempted to research things online without any luck.

Here is what I have so far, any input would be greatly appreciated.

Kindest regards,
Joseph

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
   
    const int SIZE = 500;  //Size declaration of array
    int scores[SIZE];      //Array declaration
    int count;             //Loop counter variable
    ifstream inputFile;    //Input file stream object
   
    
    inputFile.open("myTestData.txt");  //Opening the file
    if(!inputFile) cout << "Problems with file!\n";
    
    
   
    //Read numbers from file into the array
    for(count = 0; count < SIZE && inputFile >> scores[SIZE]; count++)
            inputFile >> scores[count];
               
    //Close the file
    inputFile.close();
    
    //Display the numbers in the array
    cout << "The numbers are: \n";
    for(count = 0; count < SIZE; count++)
              {
               cout << scores[count] << "";
               cout << endl;
               }

system("pause");
return 0;
}

Recommended Answers

All 9 Replies

Joseph,

The best way to deal with a problem of this sort is to open and close the file twice, or reset the file pointer to the beginning after the 1st read.

The 1st time you read through the file you don't store anything. Its purpose is simply to find how much data is there.

After determining that you read it a second time but this time you only run the loop till you get to the end of the data - which you discovered in your 1st step.

In your case, since you are statically dimensioning an array with a max of 500 elements, if there are more data in the file than 500 you mustn't read beyond 500 or you'll corrupt your memory and likely crash fairly soon after that if not immediately.

Also please use code tags which are situated at the top bar of the start thread table with (code) it will make it so much easier to read your posts - best idea not to go about declaring your a student - as long as you dont ask for code but try to learn you will be fine on this forum

Hi Joseph, welcome to the forum?

I hope your problem is already solved, jsut one remark:
Can you use CODE tags, when typing code? They are in the top of your edit controls when editing a post.

It'll look like this:

for (int n = 0; n<max_size; m++) cout << n;

welcome

Welcome!

I also hope you have solved the problem already, but it won't be from the help of the previous answers (sorry guys).

What you need to do is loop until you hit the end of the file. The end-of-file is found by simply using "inputFile.eof()". It returns true if you are at the end of the file. So your reading loop should look like:

//Read numbers from file into the array
for(count = 0; count < SIZE && !inputFile.eof(); count++)
  inputFile >> scores[count];

That's it that's all! Enjoy!

Hi Joseph, welcome to the forum?

I hope your problem is already solved, jsut one remark:
Can you use CODE tags, when typing code? They are in the top of your edit controls when editing a post.

It'll look like this:

for (int n = 0; n<max_size; m++) cout << n;

I did say the same thing ....

wow, i got sucked into a C++ matter

Welcome!

I also hope you have solved the problem already, but it won't be from the help of the previous answers (sorry guys).

What you need to do is loop until you hit the end of the file. The end-of-file is found by simply using "inputFile.eof()". It returns true if you are at the end of the file. So your reading loop should look like:

//Read numbers from file into the array
for(count = 0; count < SIZE && !inputFile.eof(); count++)
  inputFile >> scores[count];

That's it that's all! Enjoy!

eof() can have some bizzare results when not used properly. The extraction operator returns a reference to the stream. This returned reference can be used in a conditional. If the stream is "not good", the value of the stream will be interpreted as false by the conditional, otherwise it will be interpreted as true. Due to that behavior, the OP would be better off using a while loop that's based on the actual read action, it's fewer steps:

const int arraySize = 250;
ifstream inFile("someFile.txt");
int anIntArray[arraySize] = {0};
int count = 0;
while ((count < arraySize) && (inFile >> anIntArray[count])) {
  ++count;
}
commented: Yes +7

Here's how I'd do it. First make a text file and put about 10 numbers in it and call it Data.txt...

1
5
34
65
2
7
897
123
36
67

#include <stdio.h>
const int SIZE_ARRAY=500;

int main()
{
 int ar[SIZE_ARRAY];
 int iNum=0,iCtr=0;
 FILE* fp=NULL;

 fp=fopen("Data.txt","r");
 if(fp)
 {
    printf("iCtr\tar[iCtr]\n");
    printf("================\n");
    while(true)
    {
       fscanf(fp,"%d",&iNum);
       if(feof(fp))
          break;
       if(iCtr<SIZE_ARRAY)
          ar[iCtr]=iNum;
       printf("%d\t%d\n",iCtr,ar[iCtr]);
       iCtr++;
    };
    fclose(fp);
 }

 return 0;
}

Here's the output...

iCtr    ar[iCtr]
================
0       1
1       5
2       34
3       65
4       2
5       7
6       897
7       123
8       36
9       67

And here's a better version using pointers where you don't have to care about how many items are in the file at all...

//this version dynamically allocates memory for
//number of ints in file Data.txt
#include <stdio.h>

int main()
{
 int* pInt=NULL;
 int iNum=0,iCtr=0;
 FILE* fp=NULL;

 fp=fopen("Data.txt","r");
 if(fp)
 {
    while(true)               //1st find out how many ints in file
    {
       fscanf(fp,"%d",&iNum);
       if(feof(fp))
          break;
       iCtr++;
    };
    pInt=new int[iCtr];       //allocate memory for iCtr ints
    rewind(fp);               //rewind file
    printf("i\tpInt[i]\n");
    printf("===============\n");
    for(int i=0; i<iCtr; i++)
    {
       fscanf(fp,"%d",&iNum);
       pInt[i]=iNum;
       printf("%d\t%d\n",i,pInt[i]);
    };
    fclose(fp);
    delete [] pInt;
 }

 return 0;
}

Output...

i       pInt[i]
===============
0       1
1       5
2       34
3       65
4       2
5       7
6       897
7       123
8       36
9       67

...which is the general way of dealing with this sort of thing, as I originally stated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.