user2940061
user2940061

Reputation: 3

How to find the number of non null items in a char array. C++

I am doing a project for my computer science one course and I am having trouble trying to get the exact size of an array that contains char values. First off the program prompts the user to enter the char values, by using the line cin.getline(array,100); Afterwards, it takes the array and then passes it a getSize function that is suppose to return the actual size of the array. The only problem is that it is not inconsistent. Sometimes it returns the right value, but other times it doesn't. getSize function :

int getSize(char arr[]){
    int i = 0;  
    for(i; '\0' != arr[i];i++){ 
    }
    return i;
}

Example: arr[100] contains 5 characters and the rest are null, but the function returns 7 when the program runs. I am not sure if this is an issue, but the program modifies the array before sending it to the size function. It removes the duplicates.

Upvotes: 0

Views: 3969

Answers (4)

Raon
Raon

Reputation: 1286

you can easily use sizeof() operator to get size,...

if you have char a[10];

use

int size=sizeof(a);

Upvotes: 0

nishantjr
nishantjr

Reputation: 1820

Since you're dealing with arrays, use the strlen function

strlen(array);

Note that there's also a getline overload for strings that's more C++ like (object oriented etc)

std::string line;
std::getline(std::cin, line);
size_t len = line.length();

Upvotes: 4

xmllmx
xmllmx

Reputation: 42369

template<size_t t_size>
size_t GetRealSize(const char (&str)[t_size])
{
    return std::count_if(&str[0], &str[t_size], [](char c) { return !!c; });
}

This might be what you want.

Upvotes: 1

Linga
Linga

Reputation: 10563

This can't be done with pointers alone. Pointers contain no information about the size of the array - they are only a memory address. Because arrays decay to pointers when passed to a function, you lose the size of the array.

One way is to use Templates

template <typename T, size_t N>
size_t array(const T (&buffer)[N])
{
cout << "size: " << N << endl;
return N;
}

You can then call the function like this (just like any other function):

int main()
{
char a[10];
array(a);
}

Output:

size: 10

Upvotes: 0

Related Questions