c++ - 使用stof引发异常-C++

标签 c++ file csv exception

所以我有一个程序来打开一个csv文件并对其执行很多操作。现在,我需要对其进行更改,以便打开一个文本文件,该文件列出了我要在其中使用的文件的名称,然后循环执行相同的操作,直到对所有这些文件都执行了操作,而不是像以前那样只对一个文件进行了操作。我很困惑,因为我看不到这段代码片段有什么问题,因为以前从单个文件中读取代码时,它工作得很好。

在继续逐行读取文件的其余部分之前,我舍弃了每个csv文件的第一行以将它们存储为列标题。我的程序在到达此行时崩溃:

getline(datafile, unusedline, '\n');

与错误
terminate called after throwing an instance of 'std::invalid argument' what(): stof

我假设它在这里崩溃,因为ive添加了cout语句向我展示程序在哪里停止运行以及这在哪里崩溃。我有很多代码,因此请尽量使代码可读性强
ifstream infile("data\\met_index.txt"); //Open the text file thats lists the csv files needed

    if(!infile) //Exits the program and outputs this message if the file is not found
    {

        cout << "File not found.";

        return -1;

    }

    Vector<string> headers;

    while(getline(infile, files))
    {

        ifstream datafile(files.c_str());
        if(!datafile) //Exits the program and outputs this message if the file is not found
        {

            cout << "File not found.";

            return -1;

        }
        cout << "File: " << files << endl;

        cout << "Reached here so far: " << endl;

        string unusedline;
        string line;
        string token2;
        getline(datafile, unusedline, '\n');
        cout << "Testing for the first line: " << unusedline << endl;
        stringstream headers2(unusedline);
        cout << "Testing for crash" << endl;
        //This is where it crashes, after printing the above statement
        while(getline(headers2, token2, ','))
        {
            for(int x = 0; x < headers.vecsize(); x++){
            headers.add(token2);
            cout << headers[x] << endl;
            }


        }

最佳答案

由于您发布的代码不包含对stof的调用,因此我认为崩溃实际上在headers.add(token2);中。如果stof抛出invalid_argument异常,则意味着它已被赋予某些内容,无法转换为浮点数。

换句话说,问题似乎出在您的数据上,而不是您的代码上,或者代码与数据不匹配。

通常,使用PS调试器比将cout <<语句添加到代码中更容易。

关于c++ - 使用stof引发异常-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61848507/

相关文章:

c++ - 知道 CPU 是否支持纳秒

c++在参数中转发命名空间声明

c++ - 使用模板参数作为模板参数

php - 如何使用ssh删除远程文件?

ruby - FasterCSV 导入器到 DataMapper 模型 - 没有插入行

c++ - 为什么不总是使用模板而不是实际类型?

python - 如何在 Windows 上用 Python (3) 读取/写入文件而不引入回车符?

Java快速排序,从用户输入文件读取到任何数组(待排序)

java - 在java中比较2个字符串数组并打印两个数组中相同的元素

python - CSV 文件重新格式化