Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is strlen(s) different from the size of s, and why does cout char display a character not a number?

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++:

  1. 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)?

  2. 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?

like image 938
PaulP1 Avatar asked Sep 28 '18 14:09

PaulP1


1 Answers

  1. 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....
  2. 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.
like image 92
Ian Avatar answered Sep 19 '22 07:09

Ian