I've been surfing the net for hours now looking for a good example of reading and sorting data from a textfile.:pretty: But I can't find a good one that is working. :(Can somebody give me a simple example code of reading and sorting data from a textfile in ascending order plz? :icon_neutral: The textfile will just contain numbers and name just like this one

5 jose
2 juan
3 miguel
1 luis
4 manuel

and when read and sorted, it will be displayed like this

1 luis
2 juan
3 miguel
4 manuel
5 jose

Thanks in advance for someone who could help me. :icon_cheesygrin:

Do you have any code you worked on at all?
As the rules state above this section, we help those who show work.

I'll help you get started

#include <iostream>
#include <fstrea> file input output stream library
using namespace std;

int main()
{
  ifstream fin; //declare fin as a variable of input file stream which is used to read IN from a file 

fin.open("text.txt"); //open file 

//Read from file 
//Store data in array, or array of structs.
//Use a sorting algorithm to put the data in order.


return 0;
}

tnx for that but I already have a read code. What I don't know how to make is the looping and stroring of data in an array. Can you give me a simple example code of that plz? And i'll just applly it to my program.

Do you know how many items or a maximum number of items there are in the file? If not an array probably isn't the best container to hold the data, unless that it is the container type you are required to use.

Do you know about classes and structs, because they will make the task much easier.

The basic protocol for loading the array might look something like this:

declare an int to act as an index and initialize it to an appropriate value
declare an array of class objects of an appropriate size
declare an ifstream and associate it with an appropriate file

if unable to open file
{
  tell user problem occured  and exit program or do something more elegant
}

while (you are able to read in an object into the current element of the array using the ifstream and the number of objects is below the capacity of the array)
{
   increment the current index
}
This article has been dead for over six months. Start a new discussion instead.