If you have a file format that is of the form (for one entry)
1234
description here
999.99
(across multiple lines) then the explanation is simple
Th reading code in your loop, which does
stockFile >> instock[counter].itemCode;
stockFile.getline (instock[counter].description, 20);
stockFile >> instock[counter].price;
will work in this sequence
- The value of
instock[counter].itemCode
will receive the value 1234
. However (and this is important to understand) the newline after the 1234
will still be waiting in the stream to be read.
- The call of
getline()
will encounter the newline, and return immediately. instock[counter].description
will contain the string ""
.
- The expression
stockFile >> instock[counter].price
will encounter the d
in description. This cannot be interpreted as an integral value, so instock[counter].price
will be unchanged.
Assuming some preceding code (which you haven't shown) sets instock[counter].price
to 999.99
the above sequence of events will explain your output.
The real problem is that you are mixing styles of input on the one stream. In this case, mixing usage of streaming operators >>
with use of line-oriented input (getline()
). As per my description of the sequence above, different styles of input interact in different ways, because (as in this case) they behave differently when encountering a newline.
Some people will just tell you to skip over the newline after reading instock[counter].itemCode
. That advice is flawed, since it doesn't cope well with changes (e.g. what happens if the file format changes to include an additional field on another line?, what happens if the file isn't "quite" in the expected format for some reason?).
The more general solution is to avoid mixing styles of input on the one stream. A common way would be to use getline()
to read all data from the stream (i.e. not use >>
to interact directly with stockFile
). Then interpret/parse each string to find the information needed.
Incidentally, rather than using arrays of char
to hold a string, try using the standard std::string
(from standard header <string>
). This has the advantage that std::string
can adjust its length as needed. std::getline()
also has an overload that can happily read to an std::string
. Once data is read from your stream as an std::string
, it can be interpreted as needed.
There are many ways of interpreting a string (e.g. to extract integral values from it). I'll leave finding an approach for that as an exercise - you will learn more by doing it yourself.