SamJava_The_Hut
SamJava_The_Hut

Reputation: 13

Concatenating an array size in cout statement

I'm trying to output the number of element-objects in my array, but the syntax for that is not the same as it is for Java:

    // print list of all messages to the console
void viewSent()
{
    cout << "You have " << sent.size() << " new messages.\n";//Error: left of '.size' must have class/struct,union
    std::cout << "Index      Subject" << '\n';

    for (size_t i = 0; i < sent.size(); ++i)
    {
        std::cout << i << "    : " << sent[i].getSubject() << '\n';
    }
}

if the .size doesn't work in C++ syntax, what does?

Upvotes: 0

Views: 68

Answers (2)

Bill Weinman
Bill Weinman

Reputation: 2059

If your array is a C-Array, you can loop through it like this:

for (size_t i = 0; i < (sizeof(sent) / sizeof(TYPE)); ++i)

... where TYPE is the underlying type of the array.

For example, if sent is defined as:

int sent[];

... then TYPE would be int, like this:

for (size_t i = 0; i < (sizeof(sent) / sizeof(int)); ++i)

A C-Array is not an object. So it has no members or methods and you cannot use the member operator with it. The sizeof operator is used to find the size of a fundamental type, in bytes. sizeof returns an integer value of type size_t.

Upvotes: 0

M.M
M.M

Reputation: 141618

The C++ equivalent of a Java array is std::vector. sent.size() is the correct way to get the size.

You didn't post your definition of sent but it should be std::vector<YourObject> sent;, perhaps with initial size and/or values also specified.

I'm guessing you tried to use a C-style array -- don't do that, C-style arrays have strange syntax and behaviour for historical reasons and there is really no need to use them ever in C++.

Upvotes: 4

Related Questions