Search code examples
c++arraysstringsize

Using String Size to Declare Array Size?


Sorry beginner here. I'm trying to get the string size from the cin function, then use that to declare array size. But it's saying:

line 17: request for member 'size' in 'x', which is non-class type 'std::string long int'.

It works fine without the array though.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int y;
    string x[y];
    cout << "Enter sequence" << endl;
    cin >> x[y];
    y = x.size;

    for (int i = 0; i > y; i++)
        cout x[i];

    cout << "The size of the sequence is " << x.size() << " characters." << endl;
}

Solution

  • First, of all declaring an array as you do is not allowed. Let's take a look at these two lines of code

    int y;
    string x[y];
    

    In the second line of code, what is the value of y? It could be anything. Certainly the compiler doesn't know, and the array size must be determined at compile-time.

    There are two solutions to your problem:

    1. Use pointers and dynamically allocate an array.

    2. Use std::vector and let the standard library take care of the dynamic allocation.

    IMO, both are tools which you should have in your programmer tool belt, so you should learn how to do both. You should also learn the advantages and disadvantages of either approach so that you can choose the correct one to solve a problem.

    Finally, the error message that you get means that an array does not have a member called size(). If you fix this using solution 1. above, you will need to keep track of the size yourself.