You are going to have trouble with that
dataIn.eof()
too...
For 500 elements a
std::vector
is fine, but if you have a massive, unknown amount of data prefer a
std::deque
. It isn’t O(1) lookup any more, but it is still almost as good.
The advice to use a
struct
/
class
is correct:
1 2 3 4
|
struct house
{
int room, age, acre, money;
};
|
Now we write a stream extraction operator to read a “house”:
1 2 3 4 5 6
|
std::istream & operator >> ( std::istream & stream, house & h )
{
stream >> h.room >> h.age >> h.acre >> h.money;
stream.ignore( std::numeric_limits <std::streamsize> ::max(), "\n" ); // read to eol
return stream;
}
|
And finally we can write a function to load the file:
1 2 3 4 5 6 7 8 9
|
std::vector <house> read_houses( const std::string & filename )
{
decltype(read_houses("")) hs;
std::ifstream f( filename );
f.ignore( std::numeric_limits <std::streamsize> ::max(), "\n" ); // skip first line
house h;
while (f >> h) hs.push_back( h );
return hs;
}
|
Now life is extra-super easy:
1 2 3
|
auto houses = read_houses( "datafile.dat" );
...
|
BTW, when you write code, you should regularly check that it
actually compiles with the highest warning levels you can manage, and just work your way through the list of errors, one at a time, until it
does compile.
For example, C++ uses
"
for strings,
not '
. The compiler should have warned you about line 30.
Compile options I typically use:
MSVC
cl /EHsc /W4 /Ox /std:c++17 main.cpp
Clang
clang++ -Wall -Wextra -pedantic-errors -O3 -std=c++17 main.cpp
(GCC is the same as Clang, just use
g++ instead of
clang++.)
Hope this helps.
[/code]