0

I created a fixed lenght string:

string fileRows[900];

But sometimes I need more than 900, and sometimes it would be enough 500.

and after that I need to fill the array with a file rows:

...
    string sIn;
    int i = 1;

    ifstream infile;
    infile.open(szFileName);
    infile.seekg(0,ios::beg);

    while ( getline(infile,sIn ) ) // 0. elembe kiterjesztés
    {
        fileRows[i] = sIn;
        i++;
    }

How can i create dynamic lenght for this array?

1

1 Answer 1

2

use std::vector, vector is known as dynamic array:

#include <vector>
#include <string>

std::vector<std::string> fileRows(900);

Actually you could just reserve the space for elements and call push_back:

std::vector<std::string> fileRows;
fileRows.reserve(900);   

while (std::getline(infile, sIn))
{
   fileRows.push_back(sIn);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It works fine, but if i would like to read the 2. rows how can I do it? fileRows[2] doesnt work.
not before you push_back at least 2 elements. you could always check vector size before call operator[].
Ohh I found it: fileRows.at(1)

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.