Exercise where I am asked to create a string type variable named text, a character variable named letter and an integer variable named quantitat.
It then fetches a string from the input channel and stores it in the text variable, and also fetches a character and stores it in the lletra variable.
Next, use the countAppearances function to store the variable quantitat the number of times the letter appears in text. Once obtained, it displays the message "Letter" + lletra + "appears" + quantitat + "times in the texto" + text on the screen.
It gives me an error, especially in the num variable and I don't know if I have solved the exercise correctly with the for and if the function is correctly declared.
#include <iostream>
#include <string>
using namespace std;
int countApperances(string s, char c);
int countApperances(string s, char c)
{
for(int i; i < s.length(); s += 1){
int num = 0;
if(s[i] == c){
num += 1;
}
i+= 1;
}
return num;
}
int main(){
string text;
char lletra;
int quantitat;
cin >> text >> lletra;
quantitat = countApperances(text, lletra);
cout << "Letter " << lletra << " appears " << quantitat << " times in the next " << text;
return 0;
}
several things. You haven't initialized the i inside the for. Set it to int i = 0; Then your num variable is declared inside the for so when you return it you can't. Take out your num variable before the for and there it works. Also you are incrementing the string s. That will cause it to loop. Because you enlarge it on each pass. You must change is s+=1 to i++. Your fixed code would look like this:
Hope it has fit.
Greetings, a hug.
To count the number of elements E in a container C, you can use
std::count
the header function<algorithm>
:So your code could look like:
You can see it working in Try it online!.
If what you want is to implement the function
countApperances
, you have very serious errors in your implementation:The variable
num
only exists inside the loopfor
(a variable that appears between curly braces{
and}
only exists inside those curly braces):I advise you the following:
for
.Following those tips, your function
countApperances
could look like:The
for
range one is shorter and easier to write/read, the letter count uses a C++ trick: a boolean comparison (like checking if two data are equal) returnstrue
orfalse
, a boolean value can be implicitly converted to an integer being0
the value offalse
and1
the value oftrue
so the expression:It will add
1
whenletra
it isc
and it will add0
otherwise. You can see the code working in Try it online!.