Reputation: 881
int main()
{
char sentence;
int count;
cout << "Enter sentence: ";
cin >> sentence;
count = 0;
while ( sentence == 'b' || 'B' ) {
count++;
}
cout << "Number of b's: " << count * 1 << endl;
return 0;
}
The counting must also stop at all punctuation. I can't seem to get it to give me the correct count.
Upvotes: 2
Views: 4632
Reputation: 6793
#include <iostream>
using namespace std;
int main()
{
char c;
int n = 0;
cout << "Enter sentence: ";
while (cin >> c && !ispunct(c)) if (tolower(c) == 'b') n++;
cout << "Number of b's: " << n << endl;
return 0;
}
Example:
Enter sentence: Two B or not two b, that is the question Bb.
Number of b's: 2
Upvotes: 0
Reputation: 57698
It's your while
loop. The variable sentence
is not changed inside the loop, so the loop may execute forever.
You may want to use std::string
for a sentence and char
for a character in the sentence.
char letter;
cout << "Enter a sentence:\n";
while (cin >> letter)
{
// Check for sentence termination characters.
if ((letter == '\n') || (letter == '\r') || (letter == '.'))
{
break; // terminate the input loop.
}
// Put your letter processing code here.
} // End of while loop.
Upvotes: 2
Reputation: 43
#include <string>
Use string. string sentence;
And create a for long as:
for(int i=0; i<sentence.length(); i++)
if(sentence[i] == b || B) count ++;
So simple ;) Good luck ;)
EDIT 1:
If you will only use while
:
int count = sentence.length();
int count2 = 0;
while(count != 0)
{
if(sentence[count] == b||B) count2++
count--;
}
Good luck ;)
Upvotes: 0
Reputation: 3329
There are a couple suspicious points in your program:
char sentence;
cin >> sentence;
This looks like it would only be reading one character. You might want to getline() and save user input in a std::string
As for
while ( sentence == b || B ) {
This wouldn’t even compile since b and B are undefined. Maybe it should be
if ( cur_byte == ‘b' || cur_byte == ‘B’ )
count++
where cur_byte is some properly maintained iterator inside your string
Upvotes: 0