You are trying to store 14
in a char
which will not work! Everything will be fine with single digit numbers (0,1,2,3,4,5,6,7,8,9) because they are seen as a single character, but 14
contains two characters, so firstly 1
will be added in the vector, then 4
. So, the answer 11 is correct because 1+2+3+1+4=11! You can either use this solution: https://stackoverflow.com/a/289372/3185860 or the strtok
alternative to divide the input string and get the numbers (in this case, the ' '
will be your delimiter character) or parse the input in another way to store the numbers in an int
variable.
Edit: I see you still can't understand what you have to do. It took 2 minutes to modify the response from the link I commented below ( https://stackoverflow.com/a/1321175/3185860 ) to solve your problem... Next time, please spend more time trying to solve it yourself.
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
size_t ReadNumbers( const string & s, vector <int> & v ) {
istringstream is( s );
int n;
for(int i=0; i<s.size(); i++) if(isalpha(s[i]) && s[i]!=' ') return 0;
while( is >> n ) {
v.push_back( n );
}
return v.size();
}
int main() {
int sum=0;
string s;
vector <int> v;
getline( cin, s );
ReadNumbers( s, v );
if(v.size()==0){ cout<<"Invalid\n"; return 0;}
else{
for ( int i = 0; i < v.size(); i++ ) {
sum = sum + v[i];
}
}
cout<<sum<<'\n';
return 0;
}