There are two mistakes in your given code snippet:
Mistake 1
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following code is incorrect in your code as well:
char str[] ={};//this defines(and declares) an empty array. This statement is not fine(that is it is incorrect) because we cannot have 0 size arrays in c++
cin >> str; //incorrect because a built in array is fixed size container and you cannot add more elements(than its size) to it(both by user input or by the programmer itself)
Solution to Mistake 1
char str[100] ={}; //this defines an array of fixed size 100.
cin >> str; //this is correct now, but note that you can only safely enter upto 100 characters. If you try to add more than 100 than this will also become incorrect
Mistake 2
You're calculating the size of the array in the wrong way. The correct way would be :
int arrSize = sizeof(str)/sizeof(char);// since sizeof(char) = 1 you can omit the denominator but note you can omit it only for char type
Using the correct formula sizeof(str)/sizeof(char)
is important for array of other types like double
, int
etc. This is the general formula. But since sizeof(char) = 1;
so the formula that you used is correct(only for char
). So if you have an array of double
then you should use sizeof(str)/sizeof(double);
.
Also, note that you can/should instead use std::string
to take input from the user and then use size()
method to calculate how long the input was like:
std::string str;
std::cin >> str;
std::cout<<"size is "<<str.size()<<std::endl;
Note you can also use std::size
in C++17 for finding the size of the array.(pointed out by @eerorika in the comments below)