mardi 8 mai 2018

Quit-option and while loop in C++

in my method I want to be able to type in a line of strings and it will filter me out the first word as a command and the other words as parameters. Every line starts out with a cout of "$".

This should be a continuous loop until I type in "CTR_C". If I type in "CTR_C" i should get asked whether I want to quit or not. If "y" I will get out of the method, if "n" there should be "$" again and I can continue to type in my lines of strings.

Now at this part, when I type in "n", I won't get back into my while(myLoop)-loop and I get kicked out of the method instead. What mistake have I overlooked?

int read_command(char *command, char *parameters[]) { // prompt for user input and read a command line 

// getline, extract command and parameters, set noParam, ...
// ...

int noParam = 0;
bool myLoop{true};
string myCommand{};
vector<string> paramVec{};
vector<string> words;

string line;
while (myLoop) {

    cout << "$ ";


    while (getline(cin, line)) {
        int test{};
        istringstream iss(line);
        string word;
        unsigned i = 0;

        while (iss >> word) {

            if (word != "CTR_C") {
                words.push_back(word);
                ++i;
                test++;
            } else {

                string yn{};

                cout << "Do you want to quit (y/n)?" << endl;

                cin >> yn;
                if (yn == "y") {
                    myLoop = false;
                    break;

                } else {
                    if (yn == "n") {
                        cout << "nicht abbrechen" << endl;
                        myLoop = true;
                        test = 999;


                    } else {
                        cout << "Eingabe ungueltig" << endl;
                        myLoop = true;
                        test = 999;

                    }
                }


            }

        }



        if (test == 0) {
            myLoop = false;
            break;
        } else {
            if (test == 999) {

                cout << "try again" << endl;
                myLoop = true;

            } else {

                //extract command
                myCommand = words.at(0);
                cout << "Command is: " << myCommand << endl;


                //extract parameters                
                for (int i = 1; i < words.size(); i++) {
                    paramVec.push_back(words.at(i));
                }
                cout << "Param is: ";
                for (int i = 0; i < paramVec.size(); i++) {
                    cout << paramVec.at(i) << endl;
                }

            }
        }

        break;

    }

}

return (noParam);

};

Aucun commentaire:

Enregistrer un commentaire