int size = 0;
while(size < MAX_ARRAY_LENGTH && // prevent overflow.
// Will stop here if out of space in array
// otherwise && (logical AND) will require the following be true
file >> months[size] // read in month
>> temps[size][0] // read in first temp
>> temps[size][1]) // read in second temp
{ // if the month and both temperatures were successfully read, enter the loop
size++;
}
MAX_ARRAY_LENGTH
is a constant defining the maximum number of months that can be placed in the arrays.
>>
returns a reference to the stream being read so you can chain the operations together and take advantage of the stream’s operator bool
when done reading. operator bool
will return true if the stream is still in a good state.
The logic looks like
loop
if array has room
read all required data from stream
if all data read
increment size
go to loop.
You may want a test after end of the loop to make sure all of the data was read. If you’re reading to the end of the file, something like if (file.eof())
will make sure the whole file was read. If you want a year’s worth of data, if (size == ONE_YEAR)
where ONE_YEAR
is a constant defining the number of months in a year.
0
solved Read from mixed data file add items to string array and two-dimensional int array C++ [closed]