我创建了一个固定长度的字符串:
string fileRows[900];
但有时我需要900多个,有时500个就够了。
然后我需要用文件行填充数组:
...
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++;
}
如何为这个数组创建动态长度?
最佳答案
使用std::vector , vector 被称为动态数组:
#include <vector>
#include <string>
std::vector<std::string> fileRows(900);
实际上你可以为元素保留空间并调用push_back
:
std::vector<std::string> fileRows;
fileRows.reserve(900);
while (std::getline(infile, sIn))
{
fileRows.push_back(sIn);
}
关于c++ - 动态字符串数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475438/