Write a program that reads a character and a string (an entire line, which may include spaces or tabs), and outputs the number of times the character appears in the string. Hint: use getline(cin, mystring) to read the entire line including spaces. Use mystring.length() to know how many characters. But to avoid a glitch when getline gets an empty string following a cin, do the following sequence: cin >> mychar; /* get character. cin leaves the newline in the input buffer*/ cin.ignore(80,'\n'); /* remove newline from the buffer, which getline would see as empty line*/ cout << "Enter a string: "; //prompt for string getline(cin, mystring); Example program run (the user types only the word "Monday" and the letter "a"): Enter character to count: a Enter a string: Monday count = 1 Example program run: Enter character to count: a Enter a string: Today is Monday count = 2 Example program run: Enter character to count: b Enter a string: Today is Monday count = 0 #include #include using namespace std; /*program whose input is a character and a string (an entire line, which may include spaces or tabs). Outputs the number of times the character appears in the string. */ int main() { /* Type your code here. */ return 0; }
Write a
But to avoid a glitch when getline gets an empty string following a cin, do the following sequence:
cin >> mychar; /* get character. cin leaves the newline in the input buffer*/ cin.ignore(80,'\n'); /* remove newline from the buffer, which getline would see as empty line*/ cout << "Enter a string: "; //prompt for string getline(cin, mystring);
Example program run (the user types only the word "Monday" and the letter "a"):
Enter character to count: a Enter a string: Monday count = 1
Example program run:
Enter character to count: a Enter a string: Today is Monday count = 2
Example program run:
Enter character to count: b Enter a string: Today is Monday count = 0
#include <iostream>
#include <string>
using namespace std;
/*program whose input is a character and a string (an entire line, which may include spaces or tabs).
Outputs the number of times the character appears in the string.
*/
int main() {
/* Type your code here. */
return 0;
}
Trending now
This is a popular solution!
Step by step
Solved in 5 steps with 4 images