gpt4 book ai didi

c++ - 我不断收到 'std::invalid_argument' what() : stoi exception thrown for seemingly no reason?

转载 作者:行者123 更新时间:2023-11-28 04:02:42 30 4
gpt4 key购买 nike

我正在尝试读取具有以下格式的文件:1,2,4,6,8,12,12, .我想使用 getline() 和一个 stringstream 对象来分隔输入并在转换为整数后将其存储到一个 vector 中。它有效,我可以看到输出能够与数字 1 相加,但在完成转换文件中的所有数字后它仍然抛出异常。

输出:2个3个5个791313

#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;

int main (int argc, char** argv){
ifstream infile;
vector <int> vect;
infile.open("tested");
if(!infile.is_open()){
cout<<"File did not open"<<endl;
}
else{
while(!infile.eof()) {
string line;
getline(infile, line);
stringstream ss(line);
while (ss){
string p;
getline(ss, p, ',');
int x = stoi(p);
cout<<x+1<<endl;
vect.push_back(x);
}
}
int i=0;
while(i<vect.size()){
int e = vect[i];
cout<<e<<endl;
i++;
}
sort(vect.begin(), vect.end());
int j=0;
while(j<vect.size()){
int n = vect[j];
cout<<n<<endl;
j++;
}
cout<<"end reached"<<endl;
}
}

最佳答案

您的代码比需要的更复杂。您根本不需要使用 std::stoi()。因为您已经在使用 std::stringstream,所以让它为您解析整数。

#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;

int main (){
ifstream infile("tested");
if (!infile.is_open()){
cout << "File did not open" << endl;
}
else{
vector<int> vect;
string line;
while (getline(infile, line)) {
istringstream iss(line);
int x; char c;
while (iss >> x) {
cout << x + 1 << endl;
vect.push_back(x);
iss >> c;
}
}
for (size_t i = 0; i < vect.size(); ++i){
cout << vect[i] << endl;
}
sort(vect.begin(), vect.end());
for (int j = 0; j < vect.size(); ++j){
cout << vect[j] << endl;
}
cout << "end reached" << endl;
}
return 0;
}

Live Demo

关于c++ - 我不断收到 'std::invalid_argument' what() : stoi exception thrown for seemingly no reason?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59242774/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com