I have a file that consist of 30 rows and 3 column. I have to find the highest value of the second column with the year. for example the file is like :
2012 24 800
2013 20 304
2014 30 589
2015 28 400
i need to get the output 30 and 2014 , i already get the coding for finding the highest but i can't find the year. this is my coding :
ouh i misunderstood it , i though L27 is to declare the the variable in file first . i have one question . The year { } , price { } and production { } , if i'm going to explain it to other people , should i say that i read the data from file by vector ?
one more thing for L20 and 21 , i use string to print out the whole data from the file . It was based on my notes. But can i know why we use string ? and is there other way beside using string ?
std::string is the preferred c++ way of handling variable length text/characters. Another way would be to be a fixed size array of char - but that has issues re size and can be more difficult to manipulate as std::string has lots of provided member functions.
The program doesn't use a vector - and doesn't need to. It reads the file line by line and processes each line as required and the reads the next line.
int year{} is just defining year as type int with default initialisation (which for an int is 0).
Fair enough. I've always heard initialising with {} called default initialising as opposed to initialising with an explicit value. I guess some of us are a bit lax in using the 'correct' C++ terminology. Mea Culpa....... :)
defines a variable called year of type int but doee NOT provide an initial value. It's initial value is unknown (whatever happens to be in the memory locations used for this variable at the time).
int month {6};
defines a variable called month of type int and provides an initial value of 6.
int day {};
defines a variable called day of type int and initialises it with the default value for the specified type (0 for int).
for ( int year;
fromFile >> year;
)
{
// use year
}
Note that in this the very first thing that is done to the 'year' is to set its value with the fromFile >> year
Therefore, when (and if) we get to the body of the function, the 'year' has a known* value. *Well, whatever integer is in 'fromFile'.
Initialization of 'year' is not crucial, because its value will be set first.
The 'highest_price' is totally different case. The first action with 'highest_price' is to read its current value:
1 2 3
int highest_price {};
// ...
if (price > highest_price)
The initial value has to be set before the loop. Initialization is the logical place.
Furthermore, the initial value of 'highest_price' must be less or equal to lowest possible price. If it is not, then you could have case where all the prices are lower than the initial 'highest_price' and the algorithm would fail.
when i want to find highest or lowest i use the { } but when i want to find average or sum i just use int year;