Search code examples
c++loopswhile-loopdo-whilegoto

C++ how to input by word and count how much word i input


i did try using this program

#include <iostream>

using namespace std;

int main()
{
    string x;
    string a = "black";
    string b = "red";
    string c = "white";

    int e, f, g = 0; //e = black; f = red; h = white;

    cout << "input car color :";
    cin >> x;
    if (x == a) {
        cout << "continue input car color?" << endl;
    }
    else if (x == b) {
        cout << "continue input car color?" << endl;
    }




        return 0;
}

but i dont know to make the last one that show how much color did user input

this is the result for my program, how do i make it? and its in c++ btw

input car color: black                //black,red,white=user input
continue input car color? (y/n)? y
input car color: black
continue input car color? (y/n)? y
input car color: black
continue input car color? (y/n)? y
input car color: red
continue input car color? (y/n)? y
input car color: white
continue input car color? (y/n)? n

detail car color
black      3 car
red        1 car
white      1 car

Solution

  • You need to use a loop to continue prompting the user for more inputs. And you need to increment your integers on each matching input you detect.

    Try something like this:

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
        string input;
        int num_black = 0, num_red = 0, num_white = 0;
    
        do
        {
            cout << "input car color :";
            cin >> input;
    
            if (input == "black") {
                ++num_black;
            }
            else if (input == "red") {
                ++num_red;
            }
            else if (input == "white") {
                ++num_white;
            }
    
            cout << "continue input car color?" << endl;
            cin >> input;
        }
        while (input == "y");
    
        cout << endl;
        cout << "detail car color" << endl;
        cout << setw(11) << left << "black" << num_black << " car" << (num_black != 1 ? "s" : "") << endl;
        cout << setw(11) << left << "red" << num_red << " car" << (num_red != 1 ? "s" : "") << endl;
        cout << setw(11) << left << "white" << num_white << " car" << (num_white != 1 ? "s" : "") << endl;
    
        return 0;
    }
    

    Online Demo