c++ - 尝试从 csv 文件输入大量数据时出错

标签 c++

我正在尝试将数据从 csv 文件读入 C++。程序虽然编译了,但是没有输出。当我运行调试器时,我看到有一些“未处理的异常”。一个说有堆栈溢出。另一个说“0xC0000005:访问冲突读取位置 0x001000000”。我不太确定这些是什么意思,但是当我用较小的数据集测试一个非常相似的程序时,它起作用了。

在我当前的代码中,我声明了 12 个数组,每个数组代表一列。每个数组包含 537578 个元素,代表每一行。

int raw_num = 537578;
int num = 537577;
std::string raw_User_ID[537578];
std::string raw_Product_ID[537578];
std::string raw_Gender[537578];
std::string raw_age[537578];
std::string raw_Occupation[537578];
std::string raw_City_Category[537578];
std::string raw_Stay_In_Current_City_Years[537578];
std::string raw_Marital_Status[537578];
std::string raw_Product_Category_1[537578];
std::string raw_Product_Category_2[537578];
std::string raw_Product_Category_3[537578];
std::string raw_Purchase[537578];

/* 下面的数组用于后面数据类型的转换,本部分不使用*/

double User_ID[537577];
std::string Product_ID[537577];
char Gender[537577];
std::string age[537577];
int Occupation[537577];
char City_Category[537577];
std::string NumYearsInCity[537577];
bool Marital_Status[537577];
int Product_Category_1[537577];
int Product_Category_2[537577];
int Product_Category_3[537577];
double Purchase[537577];

std::ifstream infile;
infile.open("BlackFriday.csv");
if (!infile.is_open()) {
    std::cout << "File not found" << std::endl;
}
else {
    int count = 0;
    while (!infile.eof()) {
        std::getline(infile, raw_User_ID[count], ',');
        std::getline(infile, raw_Product_ID[count], ',');
        std::getline(infile, raw_Gender[count], ',');
        std::getline(infile, raw_age[count], ',');
        std::getline(infile, raw_Occupation[count], ',');
        std::getline(infile, raw_City_Category[count], ',');
        std::getline(infile, raw_Stay_In_Current_City_Years[count], ',');
        std::getline(infile, raw_Marital_Status[count], ',');
        std::getline(infile, raw_Product_Category_1[count], ',');
        std::getline(infile, raw_Product_Category_2[count], ',');
        std::getline(infile, raw_Product_Category_3[count], ',');
        std::getline(infile, raw_Purchase[count], '\n');
        count++;
    }
}

我输出了一些数组元素以确保数据输入正确,但没有输出。此外,代码退出 -1073741571 而不是 0。

最佳答案

堆栈溢出意味着您分配的内存多于堆栈中的可用内存,应用程序经常因此而终止。大数组应该分配在堆上,你可以用指针来做到这一点,但如果你没有任何限制,我建议使用 std::vector<std::string> product_id(537577);而不是 std::string ... .您可以像对待数组一样对待 vector , vector 将为您进行内存管理。

关于c++ - 尝试从 csv 文件输入大量数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719973/

相关文章:

C++ 获取虚函数表索引

c++ - 如何拥有自动递增的构建版本号(KDevelop)?

c++ - 在构造函数中初始化 <random> 类会导致段错误

c++ - Boost::signal 内存访问错误

c++ - 为什么不能在类范围内推导我的类静态自动函数的类型?

c++ - 提升精神 : how to count occurences of certain characters and then put the result in AST?

C++ 对带有 unsigned int 的重载函数的模糊调用

c++ - Linux 中的 Windows 命名管道支持

c++ - std::transform 比 for 循环慢

c++ - 如何以及何时从 malloc 返回?