c++ - 来自带有分隔符的 std::getline 的段错误

标签 c++ csv segmentation-fault

几个小时以来,我一直在尝试修复这个段错误。此代码始终在第 500 次迭代后发送 SIGSEGV。 Here's the TEST.csv I've been using .一旦 while 循环达到第二组 AMU 值,getline 立即使程序崩溃。我已经对此进行了梳理,找不到可以挽救我生命的问题。

值得注意:我无法在每台机器上重现此错误!肯定有一些内存在某处被破坏了,但我就是想不通!

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <climits>
using namespace std;
int main(int argc, char **argv)
{
    ifstream data;
    data.open("TEST.csv", ifstream::in);
    float amudata[505];
    //initialize amudata
    for (int x = 0; x < 505; x++) amudata[x] = INT_MIN;
    std::string line;
    //toss out the first 137 lines of config data
    for (int x = 0; x < 137; x++)
    {
        std::getline(data, line);
    }
    //debug iteration counter
    int x = 0;
    //toss out the first part of the timestamp
    //this is where SEGV happens
    while (std::getline(data, line, ' '))
    {
        x++;
        //toss out second part of timestamp
        getline(data, line, ',');
        //read and store the index, which is amu times 10
        std::getline(data, line, ',');
        int index = std::atof(line.c_str()) * 10;
        //read and store the amu intensity
        std::getline(data, line, ',');
        float intensity = std::atof(line.c_str());
        //some debug output
        cout << index << " " << intensity << " ";
        cout << line << " " << x << endl;
        //keep track of only the maximum intensities
        if (amudata[index] < intensity) 
        {
            amudata[index] = intensity;
        }
    }
    for (int x = 0; x < 505; x++)
    {
        printf("%f\n", amudata[x]);
    }
    data.close();
    return 0;
}

最佳答案

您的 amudata 数组太小。

处理完这一行后你的程序崩溃了:

2016/11/23 16:49:06.146,   50.500, -3.6263e-010,

当你这样做时:

int index = std::atof(line.c_str()) * 10;

line"50.500",因此设置 index = 505。然后你做:

amudata[index] = intensity;

但是 amudata 允许的索引是从 0504,所以你写在数组边界之外,这会导致未定义的行为.

你需要:

float amudata[506];
//initialize amudata
for (int x = 0; x < 506; x++) amudata[x] = INT_MIN;

而且最好不要在程序中散布这样的魔数(Magic Number),使用常量或宏。

关于c++ - 来自带有分隔符的 std::getline 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777060/

相关文章:

c++ - 当目标路径存在时 curl SFTP 重命名

c++ - 令人困惑的输出

c++ - 为什么我无法使用统一初始化来初始化字符串?

regex - 使用 awk 解析带有空字段、转义引号和逗号的 CSV

powershell - 将多个成员添加到Powershell哈希表

c - 程序给我段错误,不知道为什么

c++ - 获取 RGBDemo 的鼠标位置坐标

c - C程序中出现段错误

c - Scanf 用于多个用户输入

c# - 在 CSV 文件中编辑/保存一行