Sorry guys, am back again with another noob question and hoping someone is nice enough to help point me in the right direction.I've only began to learn this in the past couple of weeks so there is still alot am confused about. Really wish i didnt have to come here and ask dumb questions but i need to learn this by all means and nowhere else to go.
I am trying to write a program that will allow input of names in any order and sort the names based on the first character.
My code is below - it allows the names but does not sort. I know i should "store the names" somehow so i can sort and retrieve them but i dont know how.
I havent learnt sorting or array yet, just on chapter 5 of my book so i dont think i should be using those - though have tried to read-up on it but i still cant apply the concept to this simple problem.
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
int num_of_students;
int x=0;
string name;
cout << "how many student" << endl;
cin >> num_of_students;
while ((num_of_students < 2)||(num_of_students > 25))
{
cout<<"Invalid entry"<<endl;
cout<<"Please enter number greater than 2 and less than 25"<<endl;
cin>>num_of_students;
}
for (x=1; x <= num_of_students; x++)
{
cout << "enter name" << endl;
cin >> name;
}
cout << "the formation_line is: " << name << endl;
system("PAUSE");
return 0;
}
If you cannot use a container in which to store the names and then sort them the only method I can think of is to use a string and two pointers (say p1 and p2)which point to the first letter in the first name and the first letter in the last name then if p2 is lexicographically > than p1 swap them. Then increment p1 and decrement p2 and repeat.
I have based this thought on the following but am not very confident
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdlib>
usingnamespace std;
int main()
{
cout<<"this routine sorts odd string numerals to LH end\n"
<<"and even string numerals to RH end.\n";
string s;
cout<<"type in a random series of digits\n";
getline(cin,s);
int x=s.length();
cout<<"the string just typed is "<<s<<endl;
char * p1=&s[0];//p1 points to first element
char * p2=&s[x];//p2 points to last element
if(x%2==0)x=(x/2)+1;
else x/=2;
for(int i=0;i<x;i++)
{
if(*p1%2==1)*p1++ ;//advance p1 if not pointing to even number
if(*p2%2==0)*p2-- ;//reversse p2 if not pointing at odd number
if(*p1%2==0 && *p2%2==1)swap(*p1,*p2);//only swap p1 even and p2 odd
}
cout<<"\nthe sorted string is: "<<s;
cout<<"\n";
cout<<"press any key to continue. . . .";
cin.get();
return 0;
}