如何将字符串(来自具有 n 行的文件)存储在动态数组中? C++

How can I store a string(from a file with n number of lines) in a dynamic array? C++

这里是新手...学习 C++ class 数据结构。我正在制作一个程序,它从文本文件中获取杂务列表并将它们存储在动态数组中。

//In header/ In class:

private:
/* var to keep len of list */
int len = 99; // Not sure what to set this to or if I need to even set it.
/* add appropriate data structure to store list */
string *arr = new string[len];

//In .cpp:

ListOfChores::ListOfChores(string fileName) {
ifstream file(fileName, ifstream::in);
string line;
    if (file.is_open()) //Checking if the file can be opened
    {
        while (!file.eof()) // To get all the lines.
        {
            getline(file, line); // Gets a single line
            arr[len] = line; // Store a line in the array
            len++; // Increases the array size by one
        }
        file.close(); // Closes file
    }
    else cout << "Unable to open file" << endl; // Gives error if the file can't be opened
}

但是我在数组中存储一行时遇到错误。它说 "Access violation reading location." 在 main.cpp 中执行了另一个用于打印行的函数。

因为len 已经是99,所以你的数组缓冲区立即溢出。你应该有一个概念capacitylength。 Capacity是在不重新分配的情况下可以存储的最大值,length是实际的数据行数。

请避免在 C++ 代码中使用这种 C 风格的数组。使用 vector,如果我没记错的话,它已经存在了至少 20 年 (STL)。

(你不是失败者,你已经在使用 std::string :))

检查这个:

#include <vector>
//In header/ In class:

private:

/* add appropriate data structure to store list */
std::vector<string> arr;   // define a vector

//In .cpp:

ListOfChores::ListOfChores(string fileName) {
ifstream file(fileName, ifstream::in);
string line;
    if (file.is_open()) //Checking if the file can be opened
    {
       while (getline(file, line))
       {
           arr.push_back(line);
       }
        file.close(); // Closes file
    }
    else cout << "Unable to open file" << endl; // Gives error if the file can't be opened
}

现在arr.size()保存行数,不再局限于99行,而是最大。程序内存容量。您仍然可以通过 arr[12]arr.at(12) 访问第 13 行以进行边界检查访问。

迭代它的正确方法 (C++11) 例如打印所有行:

for (auto s : arr)
{
   std::cout << s << std::endl;
}

现在,如果你真的必须使用数组,你可以 emulate/mimic 做 vector 的事情(好吧,我敢肯定,不是那么高效,但可以做到):

private:

 int len=0;
 int capacity=100;
 string *arr = new string[capacity];

现在在代码中,就在插入之前(未经测试,但想法是正确的):

if (len>=capacity)
{
   string *narr = new string[capacity+100];
   for (int i = 0; i < capacity; i++)
   {
        narr[i] = arr[i];
   }
   delete [] arr;
   arr = narr;
   capacity += 100; // growth
}

(您不能使用 reallocmemcpy,因为您正在处理数组中的对象)