masschamber wrote: |
---|
Why is (file.good()) always wrong? |
while(file.good())
is wrong because istream::good() is not intended for use in a while loop condition. Same goes for
while(!file.eof())
.
Typical misuse of these functions is code such as
1 2 3 4 5
|
while(file.good()) // or while(!file.eof())
{
cin >> data; // or any other input operation
// process data
}
|
The typical symptom of this is what people report as "last line was repeated" or "while loop reads extra line". It did not actually read the extra line. It ran off the end of file, the input operation failed, and the value in the variable 'data' was not changed: it was the same value that was obtained on the previous loop iteration. Only the second time around after the end of file the eof()/good() gets a chance to break the loop.
In this case, you have two kinds of input operations:
istream::getline
, which writes a zero-length C string into the output array when it fails and i
stream::operator>>
which doesn't get a chance to execute after getline()'s failure, so the contents of
StartSalary
and
Age
remain unmodified after you run off the end of file.
As you reported,
I get an extra line minus char Name |
Natural C++ input loop is
1 2 3 4
|
while( /* input operation, such as cin >> data */ )
{
// process data
]
|
which would be in your case
1 2 3 4 5
|
while( Customer.getline(Name,25,'~')
&& Customer >> StartSalary >> Age )
{
// calculate taxes and print the results
}
|
(note that istream::getline() will pick up the trailing endline from the end of the last line, as well as the space before the '~' - you may skip the former with ws:
1 2 3 4 5 6
|
while( Customer >> ws
&& Customer.getline(Name,25,'~')
&& Customer >> StartSalary >> Age )
{
// calculate taxes and print the results
}
|
If that input operation gets too complex, turn your record into a struct with its own input/output operators, so the loop stays simple.
Also note that C++ supports strings, it may be helpful to turn Name into a
string
, in which case the input will be
getline(Customer, Name, '~') )