我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)


#include<bits/stdc++.h>
#include <iostream>
#include<string>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
string s;
cin>>s;
string x = "";
int y = 0;
for(int i = 0; i<s.length(); i++){
if(s[i] < 'A'){
x = x + s[i];
}
else if(s[i] > 'A'){
y = y + std::stoi(x);
x = "";
}
}
cout<<y;
}
}

抛出的错误是:

在抛出"std::invalid_argument"实例后终止调用 什么((: 斯托伊

参考资料说;

如果无法执行转换,则会引发invalid_argument异常。

根据我的测试,当您输入整数时它有效。因此,您可能输入的字符无法转换为整数。

#include<bits/stdc++.h>
#include <iostream>
#include<string>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
string s;
cin>>s;
string x = "";
int y = 0;
for(int i = 0; i<s.length(); i++){
if(s[i] < 'A'){
x = x + s[i];
}
else if(s[i] > 'A'){
y = y + atoi(x.c_str());
x = "";
}
}
cout<<y;
}
}

Atoi 函数对我有用,我使用了字符串的 c_str(( 作为数组并包含给定基本字符串的字符以及额外的终止空字符。

最新更新