I wrote a piece of code to count how many 'e'
characters are in a bunch of words.
For example, if I type "I read the news"
, the counter for how many e
's are present should be 3.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[255],n,i,nr=0;
cin.getline(s,255);
for(i=1; i<=strlen(s); i++)
{
if(s[i-1]=='e') nr++;
}
cout<<nr;
return 0;
}
I have 2 unclear things about characters in C++:
In the code above, if I replace strlen(s)
with 255, my code just doesn't work. I can only type a word and the program stops. I have been taught at school that strlen(s)
is the length for the string s
, which in this case, as I declared it, is 255. So, why can't I just type 255, instead of strlen(s)
?
If I run the program above normally, it doesn't show me a number, like it is supposed to do. It shows me a character (I believe it is from the ASCII table, but I'm not sure), like a heart or a diamond. It is supposed to print the number of e
's from the words.
Can anybody please explain these to me?
strlen(s)
gives you the length of the string held in the s
variable, up to the first NULL character. So if you input "hello", the length will be 5, even though s
has a capacity of 255....nr
is displayed as a character because it's declared as a char
. Either declare it as int
, for example, or cast it to int
when cout'ing, and you'll see a number.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With