Extremely confused on how I can combine quantities and words in one line when outputting?

59 Views Asked by At

I am trying to make a program which will take in a list from the user with both quantities and words. However, I have everything done but am unable to combine the numbers with according word(s) on the same line. It continues to output all the numbers and then output all the words. Also the words should be outputted in alphabetical order. Thank you in advance!

{

set<string> sortedItems;
cout <<  " (type \"exit\" to exit, now press enter to begin listing): ";

getline (cin, qtyChoice);
getline(cin, itemChoice);

for (int i = 1; ; i++)
{
string itemChoice;
string wholeOrder;
cout << i << ". ";
cin >> itemChoice;
cin >> qtyChoice; // this is how I got it to take #'s


if (itemChoice == "exit")
{
    break;
}
sortedItems.insert(qtyChoice);
sortedItems.insert (itemChoice);

for_each(sortedItems.begin(), sortedItems.end(), &print);
 return 0;

}

Instead of outputting the number of each and name of each on the same line, it does this:

1. 23 hello
2. 18 thanks
3. 37 goodbye
4. exit
exit
18
23
37
goodbye
hello
thanks
1

There are 1 best solutions below

5
john On

You need to structure your data. At the moment you are treating words and quantities exactly the same and so they print in a single list with the numbers before the words because alphabetically numbers come before words.

First create a structure for your data

struct LineItem
{
    int quantity;
    string choice;
};

Now unlike strings the compiler has no idea how to sort LineItems, you must tell it by supplying an operator< for LineItems. operator< should return true if the first LineItem is 'less than' the second LineItem. I'm assuming (perhaps wrongly) that you want to print in alphabetical order of the choices. So that would be

bool operator<(const LineItem& x, const LineItem& y)
{
    return x.choice < y.choice;
}

Then declare your set to be a set of LineItems

set<LineItem> sortedItems;

Then rewrite your input loop

for (int i = 1; ; i++)
{
    LineItem li;
    cout << i << ". ";
    cin >> li.quantity;
    cin >> li.choice;
    if (li.choice == "exit")
        break;
    sortedItems.insert(li);
}

Something like that anyway. You'll have other changes to make, for instance your print routine will have to change to use LineItems instead of strings, but I'll leave that to you.

The main is point is that by creating a LineItem struct you are grouping associated items of data (the quantity and the choice) so then you can print them together.