ofstream problem

I made a program that ask for 20 names and grade.
Then the program automatically arrange it alphabetically.
Now I tried to output the result the a ".txt" file. But the .txt file didn't arrange the names in the notepad
I want to know what I did wrong and how can I fix my program to output the 20 results alphabetically
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  #include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
 ofstream outputFile;
 outputFile.open("earlfoz.txt")
 string name[20];
 int grade[20];
 int index[20];
 int i, j;

 for(i=0;i<20;i++)
 {
  cout << "Please enter name: ";
  cin >> name[i];
  outputFile << name[i] << endl;
  cout << "Please enter grade: ";
  cin >> grade[i];
  outputFile << grade[i] << endl;
  
 }

 for(i=0;i<20;i++)
 {
  index[i]=i;
 }

 for(i=0;i<20;i++)
 {
  for(j=i+1;j<20;j++)
  {
   int temp;
   
   if(name[index[i]] > name[index[j]])
   {
    temp = index[i];
    index[i] = index[j];
    index[j] = temp;
   }
  }
 }
 cout << endl;

 for(i=0;i<20;i++)
 { 
  cout << name[index[i]] << "        "
   << grade[index[i]] << endl;
 }

 cin.ignore();
 cin.get();

 outputFile.close();
 cout << "Done!\n";
 
}
Last edited on
you sorted the names but left the grades untouched, so the (sorted) names and grades no longer match;
grade[index[i]] does not sort the grades corresponding to the name sort
one way to do this would be to have a struct student{std::string m_name; int grade;}; and sort the struct objects by name - being a struct ensures the correct grades with 'travel' with their corresponding names as these are being sorted
Hello earlfoz,

I have seen this done once before where an "index array" was used to provide a sorted order to two other arrays. Done properly it works, but I am not sure if yours is working correctly.

I would suggest scrap the "index array" and change the sort routine to sort the "name array" and "grade array" at the same time then they will be in sync.

Now I tried to output the result the a ".txt" file. But the .txt file didn't arrange the names in the notepad
I want to know what I did wrong and how can I fix my program to output the 20 results alphabetically

What you did wrong is input from "cin" and output to the .txt file before you sorted the arrays. Lines 20 and 23 need to come after the sort in a for loop to print the arrays. Something like lines 48 -52 except "cout" would be "outputFile".

Hope that helps,

Andy
Topic archived. No new replies allowed.