Hello there!

A very quick question: Can I use an already defined int as array size? I want to make an array the same length as a string.

I use ifstream to read in a random word from a file and I use .length to get the length of it and set "int wordLength" to "word.length". Now I want to create an array like: "word[wordLength]

So is it possible? I just get compiler moan when I try to do it...
Help is appreciated!

A very quick answer: You will have to use dynamic arrays

int* arr = new int[word.length];

The compiler is probably complaining that you are either trying to resize an existing array or are going outside its boundaries. If you only need a single dimension, try using vectors instead they're a little more flexible.

You can dynamically resize a vector using vectorName.resize(wordLength) . You really can't do that easily with arrays.

/* other includes */
#include <vector>

using namespace std;

int main(void) {

// pick one --V
//vector<dataType> vectorName(capacity);  //i.e. vector<char> word(length);
//  --- OR ---
//vector<dataType> vectorName(capacity, initialValue); //i.e. vector<char> word(length, 'A');

/*... read your file ...*/

/*resize the vector */
word.resize(wordLength);

/* store and manipulate your information */

return 0;
}

Oh that's nice! Thanks a lot I will try it out in a minute.

I think I'll go with vectors because vectors seem a bit simpler

Oh that's nice! Thanks a lot I will try it out in a minute.

I think I'll go with vectors because vectors seem a bit simpler

Yes, that would be a good way to do it.

Here we go!

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    
    vector<char> vectorOne(10, 'A');
	vectorOne.at(3) = 'B';
    
    for (long index=0; index<20; ++index) {
        try {
            cout << "Element " << index << ": " << vectorOne.at(index) << endl;
        }
        catch (exception& e) {
            cout << "Element " << index << ": index exceeds vector dimensions." << endl;
        }
    }
    system("PAUSE");
    return 0;
}

I found some simple code and got it working! That's awesome thanks for the help!

I'll mark it as solved :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.