I need to have it sorted in the add function by alphabetical order. (not using v
ID: 3780334 • Letter: I
Question
I need to have it sorted in the add function by alphabetical order. (not using vectors). so say the input is c a b then output would be a b c. right not it outputs in the same order as input. im using puTTY/unix compiler. language c++
[code]
#include <iostream>
#include <string>
using namespace std;
const int SIZE=100;
class library
{
public:
library();//constructor
void add(string song);
void display();
private:
string title[SIZE];
int n;
};
library::library()
{
n=0;
}
void library::add(string song)
{
title[n++]=song;
}
void library::display()
{
for(int i=0;i<n;i++)
{
cout<<title[i]<<" "<<endl;//print items
}
cout<<endl;
}
int main() {
string song;
library songs;
char answer = 'Y';
while (toupper(answer) == 'Y') {
cout << "Enter a song title: " ;
getline(cin, song);
songs.add(song);
cout << "Do you wish to continue: ";
cin >> answer;
cin.ignore(); // removes the from input file stream
}
songs.display();
return 0;
}
Explanation / Answer
#include <bits/stdc++.h>
#include <string>
using namespace std;
const int SIZE=100;
class library
{
public:
library();//constructor
void add(string song);
void display();
private:
string title[SIZE];
int n;
};
library::library()
{
n=0;
}
void library::add(string song)
{
title[n++]=song;
sort(title,title+n);
}
void library::display()
{
for(int i=0;i<n;i++)
{
cout<<title[i]<<" "<<endl;//print items
}
cout<<endl;
}
int main() {
string song;
library songs;
char answer = 'Y';
while (toupper(answer) == 'Y') {
cout << "Enter a song title: " ;
getline(cin, song);
songs.add(song);
cout << "Do you wish to continue: ";
cin >> answer;
cin.ignore(); // removes the from input file stream
}
songs.display();
return 0;
}
========================================================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ a.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Enter a song title: c
Do you wish to continue: y
Enter a song title: a
Do you wish to continue: y
Enter a song title: b
Do you wish to continue: n
a
b
c