Home > Mobile >  How to loop this program if the user input 2 or more character?
How to loop this program if the user input 2 or more character?

Time:04-25

#include<iostream>
#include<string>

int main(){
     char find;
     char find;
     int times = 0;
     string message;

    cout <<"Enter a message a message: ";
    getline(cin, message);


   cout <<"Enter a character to be found: ";
   cin >> find;


    for(int i = 0; i<message.length(); i  ){
       if(message[i]== find){
           times  ;
       }
   }
   cout <<"The character " << find <<" appeared " << times <<" times(s) in the message ";
 }

output

Enter a message: hello
Enter a character to be found: ll
The character l appeared 2 times(s) in the message 

CodePudding user response:

Try below code :

#include<iostream>
#include<string>

using namespace std;
int main() {
    string find;
    int times = 0;
    string message;

    cout << "Enter a message a message: ";
    getline(cin, message);


    cout << "Enter the character to be found: ";
    cin >> find;
    
    while (find.length() > 1) {
        cout << "Enter only 1 character to be found: ";
        cin >> find;
    }

    for (int j = 0; j < find.length(); j  )
    {
        times = 0;
        for (int i = 0; i < message.length(); i  ) {
            if (message[i] == find[j]) {
                times  ;
            }
        }
        cout << "The character " << find[j] << " appeared " << times << " times(s) in the message \n";
    }
    return 0;

}

Output:

Enter a message a message: aa bb ccc ddd
Enter the characters to be found: ab
Enter only 1 character to be found: ac
Enter only 1 character to be found: a
The character a appeared 2 times(s) in the message
  •  Tags:  
  • c
  • Related