我正在嘗試讀取 input.txt 檔案,并嘗試將每一行作為字串放入陣列中(稍后我將在初始化 obj 時使用陣列的每個元素,這就是我將每一行放入陣列的原因)。
string* ptr = new string;
// Read Mode for Input
fstream input;
input.open("input.txt", ios::in);
int size = 0;
if (input.is_open()) {
string line;
while (getline(input, line)) {
cout << line << endl;
ptr[size] = line;
size ;
}
input.close();
}
for (int i = 0; i < size-1; i ) {
cout << "array: " << ptr[i] << endl;
}
我收到錯誤訊息:
代理已分配,耗盡它
uj5u.com熱心網友回復:
不要使用陣列;使用std::vector. std::vector行為類似于陣列并使用動態記憶體:
std::string s;
std::vector<std::string> database;
while (std::getline(input, s))
{
database.push_back(s);
}
把事情簡單化。:-)
uj5u.com熱心網友回復:
正如評論中所指出的,如果您不知道檔案中有多少行,那么您需要一個在運行時根據請求增長的容器。自然的選擇是std::vector:
std::fstream input("input.txt", std::ios::in);
std::vector<std::string> lines;
std::string line;
while (getline(input, line)) {
lines.push_back(line); // std::vector allocates more memory if needed
}
for (int i = 0; i < lines.size(); i ) {
std::cout << lines[i] << std::endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480177.html
