Strcmp and strcpy help required

I can't seem to get it the name sorted, It prints in order it was entered.

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 #include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

void Sorted_Names(char Total_Names[][16], int TotalNum)
{
	int i;
	bool Sorted;
	char Temp [16];
	
	do
		{
			Sorted = false;
			TotalNum--;
			for(i = 0; i < TotalNum; i++)
					if(strcmp (Total_Names[i], Total_Names[i + 1]) != 0)
					{
						strcpy (Temp [i], Total_Names[i]);
						strcpy(Total_Names[i], Total_Names[i + 1]);
						strcpy (Total_Names[i], Temp [i]);
						Sorted						= true;
							
					}
				else;
		}
			while(!Sorted);
}


void Enter_Name(int XY)
{
	int		i = 0;
	int		Num;
	char	Total_Names[20][16] = {};
	//char	Name;

	for(Num = 1; Num <= XY; Num++)
		{
			cout << "Enter the " << Num << " Name: ";
			cin >> Total_Names[Num - 1];
//			Total_Names[Num - 1] = Name;
		}
	cout << "\tOriginal Names" << endl;
	for (int i = 0; i < XY; i++)
		cout << '\t' << Total_Names[i] << endl;

	cout << "\n\tSorted Names" << endl;
	Sorted_Names(Total_Names, XY);
	for(int j = 0; j < XY; j++)
		cout << "\t" << Total_Names[j] << endl;
}

int main()
{
	int Ask_Num;

	cout << "How many Names You Wish to Enter (1 to 20): ";
	cin >> Ask_Num;
		if(Ask_Num <= 0)
			{
				cout << "Not Valid Number, Program Terminated" << endl;
				exit(0);
			}
		else if(Ask_Num > 20)
			{
				cout << "Not Valid Number, Program Terminated" << endl;
				exit(0);
			}
		//else if(Ask_Num >= 'A' || Ask_Num <= 'Z' || Ask_Num >= 'a' || Ask_Num <= 'z')
		//	{
		//		cout << "Not Valid Number, Enter a NUMBER: ";
		//		cin >> Ask_Num;
		//	}
		Enter_Name(Ask_Num);
}
if(strcmp (Total_Names[i], Total_Names[i + 1]) != 0)

strcmp will return:

0 - if both strings are identical
less than 0 - if the "right" string comes first
greater than 0 - if the "left" string comes first

Since you are only checking to see if the value is !=0, you are only looking to see if the strings are identical or not. You are not seeing which one would come first.
I'm sorry I couldn't understand. I'm try to make sure that it start sorting/arranging names alphabetically.

if I understand of what you're saying is that I have to write two more of the if statements to check for greater or less than 0?


Also what if I turn the bool in the if statement to false and other true. would that help?
Last edited on
No. You just need two if() statements. One for strcmp() > 0 and one for strcmp() < 0.
If strcmp() == 0 you don't have to do anything.
Topic archived. No new replies allowed.