How would I order the names alphabetically?

You're supposed to be able to enter the amount of classmates (in the first line) and then write their names (e.g. 4 and Alex, Bones, Charles). Everything works out except for the last part. It doesn't print out the names in an alphabetic order. E.g. if you type in "Bones" in the last line as an answer, the program is supposed to print out Bones, Charles. Because it will start from "B" and go down in an alphabetic order, leaving behind the names with a letter that comes before the one that was written in the given name.

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
#include <iostream>
#include <string.h>
#define N 100
using namespace std;

/* Class */

int main(int argc, char** argv) {

    int n, i;
    string vet[N];
    string name;

    cout<<"Enter the amount of scholars: ";
    cin>>n;

    for(i=0;i<n;i++){
        cout<<"Enter the name of the scholar nr. "<<i+1<<": ";
        cin>>vet[i];
    }
    cout<<"Enter the name of the scholar to start from: ";
    cin>>name;
    cout<<"Alphabetically ordered names: "<<endl;
    for(i=0; i<n; i++){
        if(strcmp (vet[i], name)){
            cout<<name<<endl;
        }
    }
    return 0;
}
Last edited on
Martin324 wrote:
(e.g. 4 and Alex, Bones, Charles)

You ask for 4 students ... and then enter 3?



Martin324 wrote:
Everything works out ...

Not convinced.



Martin324 wrote:
except for the last part

Last part of what?



Martin324 wrote:
It doesn't print out the names in an alphabetic order.

Well, it's hoped that you entered the names in alphabetical order in the first place; otherwise, you will have to sort them (std::sort).



vet[i] isn't a c-string, so don't use strcmp.

vet[i] is only one array element - so it's not going to print out everything after it as well.
Perhaps:

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
#include <iostream>
#include <string>
#include <algorithm>

int main() {
	constexpr size_t N {100};
	int n {};
	std::string vet[N];
	std::string name;

	std::cout << "Enter the amount of scholars: ";
	std::cin >> n;

	for (size_t i = 0; i < n && i < N; ++i) {
		std::cout << "Enter the name of the scholar: " << i + 1 << ": ";
		std::cin >> vet[i];
	}

	std::cout << "\nEnter the name of the scholar to start from: ";
	std::cin >> name;

	std::cout << "\nAlphabetically ordered names:\n";

	std::sort(vet, vet + n);

	for (size_t i = 0, fnd = 0; i < n && i < N; ++i) {
		if (vet[i] == name)
			fnd = 1;

		if (fnd)
			std::cout << vet[i] << '\n';
	}
}



Enter the amount of scholars: 3
Enter the name of the scholar: 1: bones
Enter the name of the scholar: 2: alex
Enter the name of the scholar: 3: charles

Enter the name of the scholar to start from: bones

Alphabetically ordered names:
bones
charles

Last edited on
Topic archived. No new replies allowed.