-4

The for loop length property for arrays doesn't seem to work for me code

#include <iostream>

int main()
{
    char a[] = {"H", "e", "l", "l", "o"};
    for (int i = 0; i < a.length; i++)
    {
        std::cout << a[i];
        //I also tried printf with stdlib.h
    }
}

But it gives an error. Did I do it right?

Termininja
  • 6,620
  • 12
  • 48
  • 49

5 Answers5

3

You are using an array. It is a primitive type. So there are not member functions on it like objects. You have to use a vector instead. You also have to initialize the vector (or array) with chars not strings.

int main()
{
    std::vector<char> a = {'H', 'e', 'l', 'l', 'o'};
    for (int i = 0; i < a.size (); i++)
    {
        std::cout << a[i];
    }
}

If you really want to use an array you have to define the size function as follow:

template<class T, size_t N>
constexpr size_t size (T (&)[N]) { return N; }

int main()
{
    char a[] = {'H', 'e', 'l', 'l', 'o'};
    for (int i = 0; i < size (a); i++)
    {
        std::cout << a[i];
        //I also tried printf with stdlib.h
    }
}
El pupi
  • 458
  • 1
  • 3
  • 13
2

To get the length of an array in c++ you can use:

int length = sizeof(a) / sizeof(a[0]);

Array is not an object in c++ thus it cannot have fields.

bottaio
  • 4,963
  • 3
  • 19
  • 43
2

Plain arrays define no functions but you can use the library begin and end functions introduced with c++11:

#include <iostream>

int main()
{
    char a[] = { 'H', 'e', 'l', 'l', 'o' };  // use chars instead of strings
    for (auto it = std::begin(a); it != std::end(a); ++it)  // use iterators
    {
        std::cout << *it;
    }
}

Run on ideone.

Or even shorter using a range for as pointed out by BarryTheHatchet:

#include <iostream>

int main()
{
    char a[] = { 'H', 'e', 'l', 'l', 'o' };
    for (auto c : a)
    {
        std::cout << c;
    }
}

Run on ideone.

Keep in mind that the list initialization as above doesn't include a NULL char. If you declare your array with a NULL char at the end you can use cout directly without for loop:

char a[] = { 'H', 'e', 'l', 'l', 'o', '\0' };  // explicit NULL with list initialization
std::cout << a;

char b[] = "Hello";  // implicit NULL when using a literal
std::cout << b;
robsn
  • 734
  • 5
  • 18
1

You can't do that. You can get the size of an array a using:

   sizeof(a)/sizeof(a[0]);

But since you are in C++ you should use an std::vector like this:

  std::vector<char> a;

And then get the size:

 a.size();
DimChtz
  • 4,043
  • 2
  • 21
  • 39
0

Here a is a character array.. It doesn't have any member called "length"..This member is found in Java not C++. For this problem you can use "sizeof()" function function.

Shiv
  • 122
  • 2
  • 16