samedi 23 mai 2020

Creating " if not an integer" if statement condition (C++)

Working on an assignment where the user enters some data in a certain format (ex. "Ernest Hemingway, 9") and then its put that information in a table.

I have to take into account for errors in user input. Not putting a comma, putting too many commas, and check that the data after the "," is a valid integer.

ex. Ernest Hemingway 9

Error: No comma in string.

Ernest, Hemingway, 9

Error: Too many commas in input.

Ernest Hemingway, nine (input i am having trouble with)

Error: Comma not followed by an integer.

Ernest Hemingway, 9

Data string: Ernest Hemingway Data integer: 9

below is my current code

    int commaCount = 0; // keeps track of commas in users input
    int currentIndex = 0; // creating variable to create elements in the vectors

    do
    {
        cout << "Enter a data point (-1 to stop input) :" << endl;
        getline(cin, userInput);

        if (userInput == "-1") { break; } // meant to break out of loop if the user inputs "-1" on their first attempt

        for (int i = 0; i < userInput.length(); i++) {
            if (userInput.at(i) == ',') {
                commaCount++;
            }
        }

        if (commaCount == 0) {
            cout << "Error: No comma in string." << endl;
        }

        else if (commaCount > 1) {
            cout << "Error: Too many commas in input." << endl;
        }

        //else if ( second half of string != a POSITIVE int) "If entry after the comma is not an integer"

        else {
        breakPoint = userInput.find(',');

        listOfAuthors.push_back(userInput.substr(0, breakPoint));
        novelsPerAuthor.push_back(stoi(userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)));


        cout << "Data string: " << listOfAuthors.at(currentIndex) << endl;
        cout << "Data integer: " << novelsPerAuthor.at(currentIndex) << endl;
        currentIndex++;

        }

        commaCount = 0; // resets comma count between entries

        cout << " " << endl;
    } while (userInput != "-1"); //exits user input loop if "-1" is inputed

below is my code for how i separate the string and convert the second half into an int if it helps provide context for the code above.

breakPoint = userInput.find(',');

        listOfAuthors.push_back(userInput.substr(0, breakPoint));
        novelsPerAuthor.push_back(stoi(userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)));

Is there a way to write a condition that states something along the lines if userInput.substr(breakPoint + 1, userInput.length() - breakPoint + 1)) does not equal a positive integer, the program will print "Error: Comma not followed by an integer."

Aucun commentaire:

Enregistrer un commentaire