2016-11-30 24 views
-2

我正在學習C++,並使自己成爲超過10,000行的文本文件。我試圖創建一個字符串數組,並將第一行插入到第一個數組中,將第二行插入到第二個數組中,依此類推。以下是我迄今所做的:如何在C++中分配字符串數組?

ifstream theFile; 
string inputFile; 
cin >> inputFile; 
theFile.open(inputFile.c_str()); 
const unsigned int ARRAY_CAP = 64U; 

string line; 
string *lineArr = new string[ARRAY_CAP]; 

if (theFile.is_open()) { 
    int lineNumber = 0; 
    while (!theFile.eof()) { 
     getline(theFile, line); 
     lineArr[i] = line; 
     i++; 
    } 
} 

我的一個朋友告訴我分配的字符串數組,因爲我跑出來的內存,但我什至不知道該怎麼做。我怎麼能夠分配字符串數組?

+8

爲什麼不使用'std :: vector ''?此外,「while(!theFile.eof())」不會去做你想要的。 –

+1

使用[std :: vector](http://en.cppreference.com/w/cpp/container/vector)忘記分配。 –

+0

@JesperJuhl我也想知道如何分配數組。我的哥哥告訴我,他們一直在大學裏分配陣列。 :/ – James

回答

0

如果您想要保留動態分配的數組,您需要動態擴展它們。

unsigned int lines_read = 0U; 
std::string text_line; 
unsigned int capacity = 4U; 
std::string * p_array = new std::string[capacity]; 
while (std::getline(theFile, text_line)) 
{ 
    p_array[lines_read] = text_line; 
    ++lines_read; 
    if (lines_read > capacity) 
    { 
    // Allocate new array with greater capacity. 
    unsigned int old_capacity = capacity; 
    capacity = capacity * 2U; 
    std::string p_new_array = new std::string[capacity]; 
    std::copy(p_array, p_array + old_capacity, p_new_array); 
    delete [] p_array; 
    p_array = p_new_array; 
    } 
} 

std::vector爲您執行類似的內存管理,這樣你就不必做以上。