所以我有一个程序来打开一个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/