Ray
Ray

Reputation: 884

C++ Array Input from File

The code below is designed two input two separate .txt files. Each file has a different integer on each line. The code below reads the files, and stores each value in the index off an array. The input works great, and the cout in the while loop prints the proper value to command line.

The issue however comes with the cout << setTwo[0] << endl; outside of the loop. It prints random values as if the index of the array is not set. Im totally confused.

set2.txt

1
3
9
2

Code

int maxSize = 100;
    int setOne[maxSize];
    int setTwo[maxSize];
    int setOneSize = 0;
    int setTwoSize = 0;

//open files
ifstream fileOne ("set1.txt");
ifstream fileTwo ("set2.txt");

int number;
int number2;

fileOne >> number;
fileTwo >> number2;

//declare arrays
for(int i = 0; i < maxSize; i++) {
    while (fileOne.good()) {
        setOne[i] = number;
        cout << "set 1 " << setOne[i] << endl;
        fileOne >> number;
        setOneSize += 1;
    }

    while (fileTwo.good()) {
        setTwo[i] = number2;
        cout << "set 2 " << setTwo[i] << endl;
        fileTwo >> number2;
        setTwoSize += 1;

    }
}

cout << setTwo[0] << endl;

Upvotes: 0

Views: 171

Answers (2)

user3581454
user3581454

Reputation: 101

Well, I believe it should print quite deterministic values, in your example, it's always 2.

Code you wrote is bad, firstly, you forgot to initialize variables number and number2.

Secondly, in while loops, you constantly overwrite first element in both arrays with last read value, which leads to value 2 in setTwo[0] at the end of execution.

Thirdly, initializing arrays with non-const variable indicating size isn't actually standard in c++.

Upvotes: 3

Thomas Matthews
Thomas Matthews

Reputation: 57749

I suggest you get reading of one file working first.

In general, arrays are not used when reading from a file because the file length will vary but arrays are of fixed length. Your data in the file does not state the quantity of items.

Thus I will present a solution using std::vector followed by using an array.

std::vector<int> container1;
int number = 0;
while (fileOne >> number)
{
  container1.push_back(number);
}

Reading into arrays, if you must.
Again, the std::vector is the safer approach.

#define ARRAY_CAPACITY 100
int setOne[ARRAY_CAPACITY];
int index = 0;
int number = 0;
while ((fileTwo >> number) && (index < ARRAY_CAPACITY))
{
    setTwo[index] = number;
    ++index;
}

There is advantage to reading two files in a for loop. If one fails but the other doesn't, adds complications. Read them one at a time.

Upvotes: 1

Related Questions