szuniverse
szuniverse

Reputation: 1146

dynamic string array c++

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?

Upvotes: 0

Views: 1190

Answers (1)

billz
billz

Reputation: 45450

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);
}

Upvotes: 2

Related Questions