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

标签 c++ arrays dynamic access-violation

这里是新手...学习数据结构方面的 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
}

但是我在数组中存储一行时遇到错误。它说“访问违规阅读位置”。在 main.cpp 中执行了另一个用于打印行的函数。

最佳答案

因为 len 已经是 99,所以您立即溢出了数组缓冲区。您应该对 capacitylength 有一个概念。容量是无需重新分配即可存储的最大值,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;
}

现在,如果您真的必须使用数组,您可以模拟/模仿 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 因为您正在处理数组中的对象)

关于c++ - 如何将字符串(来自具有 n 行的文件)存储在动态数组中? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551691/

相关文章:

Java将文件读入char二维数组

matlab - 在循环内更改 for 循环索引变量

c++ - 为什么我的代码没有设置变量?

c++ - 具有特殊字符的 QFileDialog 问题

c++ - boost program_options : help vs. 有意义的选项

r - dynlm和dlm是否具有相同的数学表达式?

python - 在 Python 中从文本文件导入数据和变量名称

c++ - 如何在选中/取消选中时更改 QToolBar 上 QAction 的图标?

javascript - Array.splice 会导致内存泄漏吗?

c - 需要有关 C 语言声明的帮助