C++ compiler g++ 17 GCC 9.1.0
I was trying to convert the digts that are present in the string and sum them up but i was not able to do it, on geeksforgeeks article I found out that they used atoi and coverted the string to c style string using c_str(). After reading about atoi and stoi I found out that atoi does not report error and hence is not adviced to use. Here it seems like the issue of atoi not reporting error is helping, I am not sure though. Can someone tell me why atoi is working and stoi is not, and is there anyother way in which stoi wont give me the error.
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s; // s has 1xyz23
int n = s.size();
int i = 0;
int sum = 0;
while(i < n){
string temp = "";
while(i < n && isdigit(s[i])){
temp.push_back(s[i]);
i++;
}
cout<<temp<<" "; // o/p is 1 23 output spacing is weird though
int temp_int = atoi(temp.c_str());
sum += temp_int;
i++;
}
cout<<sum; // sum is 24
return 0;
}
1 23 24 (weird spacing is shown as a comment in the code)
Why does the above code produce the output I want but the below one produces an error.
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s; // s has 1xyz23000
int n = s.size();
int i = 0;
int sum = 0;
while(i < n){
string temp = "";
while(i < n && isdigit(s[i])){
temp.push_back(s[i]);
i++;
}
cout<<temp<<" ";
int temp_int = stoi(temp);
sum += temp_int;
i++;
}
cout<<sum;
return 0;
}
terminate called after throwing an instance of 'std::invalid_argument' what(): stoi Command terminated by signal 6