0

我即将完成我的练习程序,但我被困在将用户输入存储在未指定大小的数组中..

请看一下我的代码:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <ctype.h>
#include <cstring>

using namespace std;

int main()  {

    string items[9][3] = {{"A","BALOT","25.00"},
                            {"B","CANTON","20.00"},
                            {"C","NIDO","100.00"},
                            {"D","KETCHUP","50.00"},
                            {"E","MAGGI","15.00"},
                            {"F","ALASKA","60.00"},
                            {"G","VINEGAR","25.00"},
                            {"H","OIL","70.00"},
                            {"I","COKE","10.00"}};

    // PARA MAPRINT YUNG ARRAY.
    cout << "MANG JUAN'S 10-DAHAN\n\n";
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 3; j++)
            cout << items[i][j] << ( (j < 2) ? "-" : "\t" ); 

        if (i < 6) {
            cout << "\t";
            i += 2;
        }
        else if (i != 8) { 
            cout << "\n";
            i -= 6;
        }
    } // END OF ARRAY PRINTING

    char choice, addAnother;
    int ctr = 1, quantity = 0;
    string purchased;
    double price = 0, grandTotal = 0, total = 0;

    cout << "\n\nWOULD YOU LIKE TO PURCHASE? Y/N\n\n";
    cin >> choice;

    if(choice == 'n' || choice == 'N') {
        cout << "THANK YOU.";
    }
    else if(choice == 'y' || choice == 'Y') {

        string numPref;
        while (true) {
            if(ctr > 11) {
                cout << "\n\nTHE SYSTEM EXCEEDED ITS LIMIT\n\n";
                break;
            } else {
                if(ctr == 1) numPref = "st";
                else if(ctr == 2) numPref = "nd";
                else if(ctr == 3) numPref = "rd";
                else if(ctr > 3) numPref = "th";
            }
//rows:
            //for(int r = 0; r < 9; r++) {
            cout << "\n\nPLEASE ENTER " << ctr << numPref << " ITEM:\t";
            cin >> purchased;

            char upp = purchased[0];
            upp = toupper(upp);
            purchased = upp;

            if(!cin) { 
                cout << "Letters only";
                break;
            } else {
                if(true) {
                    cout << "HOW MANY? ";
                    cin >> quantity;
                    if(!cin) {
                        cout << "Enter number only. ";
                        break;
                    } else {
                        cout << "PRICE PER ITEM: ";

                    ///////// Look for the element and print the entire row /////////////
                        string *matchedRow;
                        const int length = 9;
                        for (int i = 0; i < 9; i++) {
                            string *oneRow = items[i];
                            /**if (oneRow[0] != purchased) {
                                cout << "\n\nNO ITEM FOUND!\n\n";
                                ctr--;
                            } else {
                                matchedRow = oneRow;
                                cout << matchedRow[2];
                                price = atof( matchedRow[2].c_str() );      
                                total = price * quantity;
                                grandTotal += total;    
                            } */

                               if(oneRow[0] == purchased) {
                                    matchedRow = oneRow;
                                    cout << matchedRow[2];
                                    price = atof( matchedRow[2].c_str() );                              
                                    total = price * quantity;
                                    grandTotal += total;

                                    if(oneRow[0] != purchased) {
                                        cout << "NO MATCH FOUND!" << endl;
                                        ctr--;
                                        break;
                                    }

                                }

                        } // End of for-loop for *matchedrow
                        ////////////////////////////////////////////
                        cout << "\n\nADD ANOTHER ITEM? Y/N " << endl;
                        cin >> addAnother;
                        if(addAnother == 'y' || addAnother == 'Y') {
                            ctr++; 
                        } else if(addAnother == 'n' || addAnother == 'N') {
                            // print the receipt here
                            goto receipt;
                             //break; // replace break with goto later
                        } else {
                            cout << "\n\nINVALID INPUT." << endl;
                            break;
                        } // End of if and else for addANother
                    }



                    } // end of else - if (!cin) for quantity input check
                } // end of char check

            //} // End of else for (!cin)     //spare bracket

        } // End of while-loop for numPref
        //} // end of rows for-loop 
    } // End of else if (choice)
receipt:
    cout << "YOUR PURCHASE:" << endl;
    cout << "NET TOTAL: " << grandTotal << endl;
    system("PAUSE");
    //return 0;

}

我想像这个示例运行一样输出购买摘要:

WOULD YOU LIKE TO PURCHASE? Y
PLEASE ENTER 1st ITEM: A
HOW MANY? 2
PRICE PER ITEM: 25.00

ADD ANOTHER? Y

PLEASE ENTER 2nd ITEM: B
HOW MANY? 1
PRICE PER ITEM: 20.00

ADD ANOTHER? N

YOUR PURCHASE:
// will display all the ordered item
// sample output
A     BALOT     50.00
B     CANTON    20.00

NET TOTAL: 70.00
4

2 回答 2

0

-正如有人提到的,这里需要抽象,但如果你愿意,你可以选择实现它

#include <deque>
#include <string>
#include <iostream>
#include <limits>
#include <cstdlib>
#include <iomanip>
#include <cctype>

using std::cout;
using std::endl;
using std::cin;
using std::string;

typedef std::deque<string> dstr;
typedef std::deque<dstr> ddstr;

struct purchase_index {
    string name;
    double amt;
    struct purchase_index *next;
} purchases;

const char *prefix[] = {"st", "nd", "rd", "th"};


int query( const unsigned );
void print_options(ddstr &);
unsigned add_purchase( purchase_index *, ddstr & );
void clrscr();
void print_purchase_hist(struct purchase_index *, char = '$');

int main() {
    ddstr items = {{"A","BALOT","25.00"},
          {"B","CANTON","20.00"},
          {"C","NIDO","100.00"},
          {"D","KETCHUP","50.00"},
          {"E","MAGGI","15.00"},
          {"F","ALASKA","60.00"},
          {"G","VINEGAR","25.00"},
          {"H","OIL","70.00"},
          {"I","COKE","10.00"}
    };

    struct purchase_index *ptr = &purchases;

    unsigned char prompt = 'y'; 
    cout << "\n\nWOULD YOU LIKE TO PURCHASE? ";
    int purchase(1);

    while ( (cin >> prompt) and (prompt|32) == 'y' ) {
        print_options(items);
        if ( !query(purchase) ) break;
        else if ( add_purchase(ptr, items) ) {
            purchase++;
            ptr = (ptr->next = new struct purchase_index());
        }
        cout << "ADD ANOTHER? ";
    }

    print_purchase_hist(&purchases);

    return 0;
}

void print_purchase_hist(struct purchase_index *hist, char currency) {
    cout << "\n\nYOUR PURCHASE:\n";
    struct purchase_index *ptr = hist;
    while (ptr->next != NULL){
        cout << ptr->name << "\t" << currency << ptr->amt << '\n';
        ptr = ptr->next;
    }
}

inline void clrscr() {
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    cout << std::setfill('\n') << std::setw(2) << '\n';
}

unsigned add_purchase( purchase_index *ptr, ddstr &itm ) {
    unsigned char w;
    unsigned num, index, ret(1);
    if ( !(cin >> w) or (index = (toupper(w) - 65)) >= itm.size() ) {
        cout << "NO MATCH FOUND!\n";
        ret = 0;
    }
    else if ( cout << "HOW MANY? " and !(cin >> num) ) {
        cout << "Enter Numbers only.\n";
        ret = 0;
    }
    else {
        ptr->name = itm[index][0] + "\t" + itm[index][1];
        ptr->amt = (double)num * atof(itm[index][2].c_str());
    }
    clrscr();
    return ret;
}

void print_options(ddstr &ref) {
    cout << "Items you can purchase:\n";
    for ( auto desc: ref ) {
        cout << "\t";
        for ( auto spec: desc )
            cout << spec << " ";
        cout << endl;
    }
}

int query( const unsigned item_list ) {
    if ( item_list > 11 ) {
        cout << "\n\nTHE SYSTEM EXCEEDED ITS LIMIT\n\n";
        return 0;
    }
    unsigned last = item_list % 10;
    cout << "PLEASE ENTER THE " << item_list
        << ( last == 0 || last > 3 ? prefix[3] : prefix[last-1] )
        << " ITEM: ";
    return 1;
}

样品运行:

WOULD YOU LIKE TO PURCHASE? y
Items you can purchase:
    A BALOT 25.00 
    B CANTON 20.00 
    C NIDO 100.00 
    D KETCHUP 50.00 
    E MAGGI 15.00 
    F ALASKA 60.00 
    G VINEGAR 25.00 
    H OIL 70.00 
    I COKE 10.00 
PLEASE ENTER THE 1st ITEM: e
HOW MANY? 3


ADD ANOTHER? y
Items you can purchase:
    A BALOT 25.00 
    B CANTON 20.00 
    C NIDO 100.00 
    D KETCHUP 50.00 
    E MAGGI 15.00 
    F ALASKA 60.00 
    G VINEGAR 25.00 
    H OIL 70.00 
    I COKE 10.00 
PLEASE ENTER THE 2nd ITEM: c
HOW MANY? 5


ADD ANOTHER? n


YOUR PURCHASE:
E   MAGGI   $45
C   NIDO    $500
于 2013-09-02T09:09:57.860 回答
0

您不能有未指定大小的数组。改为使用vector,例如:

#include<vector>
...    
vector<string> user_inputs;
string purchased;
cin >> purchased;
user_inputs.push_back(purchased);  //adding to vector

然后你可以取回你的输入:

for (int j = 0; j < user_inputs.size(); j++)
    cout << user_inputs[j];
于 2013-09-02T06:30:21.380 回答