Hello bogdyby,
You wanted some advice so here it is.
When posting your code leave out the line
#include "pch.h"
. Some people will complain about it and most people can not use it because they are using a different IDE. Even though I use VS2017 I do not use this file as I create empty projects to work with and this file is not needed.
using namespace std; // <--- Best not to use
.
An aletrnative would be:
1 2 3
|
using std::cout; // <--- Better choice.
using std::cin;
using std::endl;
|
Line 8. Use better variable names. "f" may seam easy to type and you know what it is, but others find it hard to follow. I like to use "outFile" or even "fOut" is better.
The same is true for your other variables.
Line 15.
while (!f.eof())
I do not know why people teach this. This is a bad idea as it does not work the way you think it
will. Generally by the time the while condition determines that "eof" has been reached you will
have processed the last read twice and wondering why it shows up twice.
What happens is the while condition is checked and “eof” has not been set yet. After entering the
while loop you read the last line or bit of information from the file process the information
reach the bottom of the while loop. At this point “eof” has not been set yet and you return to the
while condition which is still good. After entering the loop you try to read from the file, but
now there is nothing left to read and “eof” is set, but you do nothing at this point to deal with
the “eof” condition. So you process what information is in the variables from the last read before
returning to the while condition where it finally detects the “eof”, but you have processed the
last good read twice unless you have cleared the variables at the end of the while loop in which
case the last process will be blank.
A more acceptable way of using the while loop is:
|
1 2 3 4 5
|
while (infile >> someVariable)
{
infile >> additionalVariables;
// Additional code.
}
|
In the above example you can set up the while condition to read one variable, two or more
variables or use “std::getline(?, str)” where ? could be from “std::cin” or from a file stream
and “str” represents any “std::string” variable.
|
After that I can not tell if the rest of the while is working without an input file to use.
Your for loops look right and you close the file stream before the program ends.
Although the
return 0;
at the end of "main" is not a requirement it is good form and can be useful as a break point in the IDE when testing.
Your program uses an input file. It would be nice if you include this file in a post or at least a fair sample so everyone is working with the same information.
Hope that helps,
Andy