need to read integers that are stored in a .dat file. They must be read, then each integer put into an array of integer type.
this is what i have so far .. not much i know. but ive figured out how to do strings to a string array. now im stuck on integers. HM due soon Please Help !!
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void getHighs()
{
ifstream highDat("Highs.dat", ios :: out);
if (highDat.fail())
{
cout << "ERROR: Cannot open the file. \n" ;
system("pause");
}
}
#include <iostream>
#include <fstream>
#include <vector>
int main(){
std::vector<int> mynumbers;//use array i did this so u get to do something
std::ifstream numberfile;
int i; //needed to iterate between file and vector/array
numberfile.open("Myfile.dat");//opens file
while(numberfile.good()){
//will generally go untill end of file. it is better if you how long the file is
numberfile >> i; //gets number
mynumbers.push_back(i);//adds number to end of the array
}
numberfile.close();//remember to close the file
return 0;
}
if you are looking to cover exceptions you need to do numberfile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
and then look up try/throw/catch statements.
Just to add on to ui uiho, instead of while (numberfile.good()) I would check to see if it opened correctly, like you do with if (highDat.fail()) and then use while (!highDat.eof()) Which checks to make sure it is not end of file to loop through.
Ok i got that to work and i thank you very much i was stuck on this. kept googling read integers from dat file C++ and kept chasing myself in circles.
it says i may not change the direction of teh arrays content. does this type of an array store data in a certain way ? (noob i know) is there a such thing as a vertical or horizontal array ? i can only think to accomplish that youd have to use a two dimmensional array ( to get vertical storage). Except assignment specifies to use one dimensional arrays.
So does vector or arraylist or linked list have anything to do with this ? do those store in certain directions ? or is it just its data type ?
while(numberfile.good()){
//will generally go untill end of file. it is better if you how long the file is
numberfile >> i; //gets number
mynumbers.push_back(i);//adds number to end of the array
}
This isn't very robust. What happens when numberfile >> i fails? We treat it as if it didn't. This suffers from the same fault the .fail() and .eof() versions do.
1 2
while ( numberfile >> i )
myNumbers.push_back(i) ;
is a better solution.
ok no it doesnt work .. seems when i try to output numberfile[1] or any other position it displays 0.
numberfile[1] should cause an error during compilation.
Just using .good() to check to see if it's the end of the file is not a very good way. The way I showed, the first bit checks to see if the file opened correctly, then runs until the end of the file.
Cire: How exactly does .push_back(i) work? What are the advantages over while(!file.eof())?