C++ Homework: Parallel Arrays from text file -
i have load 3 arrays text file homework , can't figure out why isn't working. text file like:
jean rousseau 1001 15.50 steve woolston 1002 1423.20 michele rousseau 1005 52.75 pete mcbride 1007 500.32
it's name on 1 line, id number , balance due on next line separated space.
this function import data:
void inputfromfile(string filename, int sizes, string namesar[], int idsar[], float balancesar[]) { // variables int indexcount; ifstream infile; // initialize indexcount = 0; infile.open(filename.c_str()); while(infile && indexcount < sizes) { getline(infile, namesar[indexcount]); infile >> idsar[indexcount]; infile.ignore(1000, '\n'); infile >> balancesar[indexcount]; infile.ignore(1000, '\n'); indexcount++; } infile.close(); }
this gets added array when output items...
jean rousseau
1001
0
-1
3.76467e-039
36
3.76457e-039
0
6.57115e-039
7736952
8.40779e-045
7736952
0
infile >> idsar[indexcount]; infile.ignore(1000, '\n');
you read first number line, ignore characters until end of line, including second number. try read next name if number, , since aren't doing error checking, goes wrong.
this ignore
entirely unnecessary: there nothing ignore between first , second numbers >>
skip on leading whitespace. second ignore
is necessary, since have skip newline @ end of numbers line before using getline
read next name line. may easier use getline
read data file, parse numbers line using stringstream
. mixing formatted extraction (>>
) line-based extraction can difficult right.
after input operation, must check state of stream ensure error did not occur. simple example:
if (!(infile >> idsar[indexcount]) { /* input failed; handle error appropriate */ }
a stream has number of state flags , when extraction fails, fail
flag set , must cleared before continue using stream.
Comments
Post a Comment