Array of strings

How can I figure how many elements is array of strings(the strings are diferent length
Thanks
I don't think you can. You will need to keep track of how many strings you stick into that array. Better yet, use vectors:

1
2
3
4
5
vector<string> MyStrings;
MyStrings.push_back("Hello");
MyStrings.push_back("Another string");

cout << "Number of strings saved: " << MyStrings.size();


If you wanted to do something similar with arrays you'd do this:
1
2
3
4
5
6
int size = 0;
string MyStrings[100];
MyStrings[size++] = "Hello";
MyStrings[size++] = "Another string";

cout << "Number of strings saved: " << size;


You could make a class if you like that is somewhere in between:
1
2
3
4
5
6
7
8
9
class STRINGS
{
    int _size;
    string _string[100]; // If you dynamically allocate this it's essentially the same as vector
public:
    STRINGS() { _size = 0; }
    void push_back(string in) { _string[_size++] = in; }
    int size() { return _size; }
};


This would let you:
1
2
3
4
5
STRINGS MyStrings();
MyStrings.push_back("Hello");
MyStrings.push_back("Another string");

cout << "Number of strings saved: " << MyStrings.size();
Last edited on
Topic archived. No new replies allowed.