How to compare numbers inside a txt file

Hello everyone... I have been using C++ for a while now and I still have trouble solving some of the questions.... =.=

Before I start, let me say thank you for taking the time to answer my question...

My problem is this: I am trying to read a file that has several numbers inside -
200
130
123
1231
....

and I want to be able to compare a certain number of rows and print out the smallest number. Example:
200
130
123
1231
so comparing these four rows, the smallest number would obviously be 123...

I appreciate any feedbacks! ^^
Last edited on
Read them into a std::vector and sort it. Do you know how to use std::fstream?
erm... yeah I know how to read the file... but I am not sure how to read them into a std::vector..
It's as simple as this:

1
2
3
4
5
6
7
std::ifstream ifs("file.txt");
std::vector<int> vec;
int n;
while(ifs >> n)
{
    vec.push_back(n);
}
Thanks!....... er... then how do you sort it? Sorry I am more used to arrays than vectors... -.-"
You can sort vectors just as you'd sort arrays, only you have to pass iterators to std::sort instead of pointers:

std::sort(vec.begin(), vec.end());

begin() returns an iterator to the first element, while end() returns an iterator to one past the last element. Iterators are meant to behave just like pointers, so just think of them as pointers that can only point to elements in a certain container.
Again thanks for the help... but I am still a bit confused... what if the file I have reading have two columns? How do I read both columns using std::vector?
operator>>() skips whitespace so you can still use the snippet above to read two columns into one vector, or you could expand it to write the values into separate vectors:

1
2
3
4
5
while(ifs >> n >> m)
{
    vec1.push_back(n);
    vec2.push_back(m);
}
Thanks!! Finally got it to work!! XD
Topic archived. No new replies allowed.