Hello, Im trying to pass values in the txt file to my array. But my program is not able to do that. It gets an error about break or something like that. I would like to know how to fix this.
#include<cmath>
#include<string>
#include<iostream>
#include<fstream>
usingnamespace std;
int main ()
{
int n; // number read from file
int list[5];
ifstream inFile; // the input file
inFile.open("number.txt");
// Exit if there was an error
// opening the file
if (!inFile)
{
cout << "Error opening input" << endl;
return -1;
}
// Loop through the input file
while ( !inFile.eof() )
{
inFile>> n;
for(int i = 0; i <= 4; i++)
{
list[n];
}
}
// close the input file
inFile.close();
cout<<list[2]; // the number i want to output
system("pause");
return 0;
}
while(!inFile.eof()) is usually wrong. I don't think you actually need it because you are already using a for loop. You should put inFile>> n; inside the for loop or otherwise all the array elements will be set to the same value.
Trying not to change your code so much, there's one option:
int n will no longer serve as an intermediate, it will the iterator for entering each int of the array. first time, you assign the first number of you file to list[0], second time to list[1], and so on...
obviously, as pointed by peter, you had a problem with your loops, I suggest you get rid of the "for" one.
1 2 3 4 5 6 7
n=0; // To refer each block of the array
while ( !inFile.eof() )
{
inFile>> list[n]; //assigning the content of the block of the array
n++; //increasing each time by 1
}
What I'm not sure is how actually works the >> operator, don't know if it will stop after each blank space, or else...? I think it's way better to use getline, strings and stringstream, but nevermind...