line 11 doesn't do what you think,
'b'|| 'B'
is a boolean, in this case
true
. You're searching for boolean
true
in your string. It's the same as trying
word.find(true);
lines 12 and 11 indeed does nothing.
string::npos
is not a condition, it's a literal, returned from
string::find()
, what you've done is the same as saying
if(3)
In fact, in that while loop, the only statements that have any effect are lines 18, 21 and 22.
==
is not the same as
=
, and if it were, lines 19 and 20 would still be wrong.
=
assigns the value of whatever is on the right to whatever is on the left. The result is the value assinged
==
compares the value on the right to the value on the left, the result is either true or false.
A lot of unnecessary variables and type abuse.
I've made a few modifications, as a learning venture, enough to point out some (not all) the problems, and deliver a program that builds, and runs correctly. You'll have to find and fix the others yourself, you'll also have to handle istream errors yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string LowerCase(const string &str)
{
string lc("");
for (auto &c : str) lc += tolower(c);
return lc;
}
int main()
{
size_t count=0;
size_t totalSum=0;
string word;
const string endProgram("stop");
cout << "To end program enter '" << endProgram << "'" << endl << "Enter a word: ";
cin >> word;
while (word != endProgram)
{
string lcWord = LowerCase(word); // convert word to lower case
size_t pos = lcWord.find('b');
while (string::npos != pos)
{
++count; // find all occurrences of 'b' in sword
pos = lcWord.find('b', pos + 1);
}
totalSum += word.size(); // accumulates num of letters in word
cout<< "Enter another word:"; // so it keeps asking for new words
cin >> word;
}
double percentage = (count * 100.0) / totalSum;
//gives the percentage of time 'b' occurs
cout<< "The percentage of the letter 'b' contained in all the words is " << percentage << endl;
}
| |
Edit:
This might seem obvious but...
h and were only allowed to use if/else statements and loops. |
If you're not allowed a function or ranged for, then inline the code and use a traditional for loop. Be careful about out-of-bounds indexing