Search code examples
c++arraysvariablesoutputsize

Determining the size of a array which was passed a value


#include <iostream>
using namespace std;
int main(){
    char word[100];
    char count;
    int j=0;
    cout<<"Enter a word or a phrase"<<endl;
    cin>>word;
    cout<<endl<<word<<endl;
    j=sizeof(word);
    cout<<j;
}

What I want to do in the above program is to find out the length of the string(word) that was inputted by the user, but the above program just gives the size of the whole array which is 100.


Solution

  • The size of the array is, indeed, 100.

    But you're looking for the number of characters set inside that array until the first null byte, i.e. the length of the "C-string" inside the array.

    strlen does that.

    You'd be much better off with a nice std::string though, if for no other reason than you currently perform no bounds checking, so if your user inputs text of 100 characters or more, you'll overflow your array. This is at best a nasty bug, and at worst a common security risk.