简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM