Help with strings and functions


I need help using a function to determine the first and last names shown in alphabetical order so far this is all I got.

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
 #include <iostream>
#include <string>
#include <fstream>
using namespace std;
 string showfirst(string, string);
int main()
{
  int number;
  string name;
  ofstream outputFile;

  do
  {
  outputFile.open("people.txt");
  cout << "Enter the number of students\n";
  cin >> number;

  if (number <= 0)
    cout << "You can not enter a number less than or equal to zero\n";

  } while (number <= 0);


  for (int studentNumber = 1; studentNumber <= number; studentNumber++)
       {
        cout << "Enter student name " << studentNumber << endl;
        cin >> name;


       }
    
    
    return 0;
}
Last edited on
You should try the "sort" function declared in the algorithm header.
Documentation can be found here http://en.cppreference.com/w/cpp/algorithm/sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>


int main()
{
    std::vector<std::string> v {"Capt.America", "Spike", "McDonalds", "Applejack"};
    std::sort(v.begin(), v.end(), [](const std::string &lhs, const std::string &rhs) -> bool {return lhs[0] < rhs[0];});
    for (auto &x : v)
        std::cout << x << std::endl;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.