0

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;
}
9
  • 4
    You can't declare arrays with a runtime size. Use std::vector for that. You might also be confusing the condition of a for loop. Commented Nov 29, 2012 at 0:10
  • I haven't learned about vectors yet, is there another way? Commented Nov 29, 2012 at 0:11
  • 1
    I think what you're going for is just std::string x; std::cin >> x; std::cout << x;. It plays nicely with input and output. It looks like you're trying to use a combination of std::string and char[]. Aside, vectors are much simpler than the other way, though. Commented Nov 29, 2012 at 0:12
  • 2
    @Foxic: No. Learn about vectors now and you'll be a better person for it. It's worth the 30 minutes of your time. Commented Nov 29, 2012 at 0:15
  • 1
    Also, I'd like to back up and ask what you are trying to do. The title of your question doesn't exactly match the code. What is the problem you are trying to solve here? Commented Nov 29, 2012 at 0:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ha, I was so knackered when I answered that question.. actually went to bed immediately after :) Surprised there wasn't a great amount of downvotes. +1 For correct answer :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.