-3

The problem is to print sum of all integers in one input line.If any of the input is not valid print "Invalid". This is the code --> C++ Code Link

The problem with the code is that it doesn't produces output if input > 9

.How should I approach here?

input : 1 2 3 14
output : 11 //which is wrong
input : 1 a 2 b
output : Invalid 
close2zero
  • 85
  • 8

3 Answers3

1

At line 16 of your code:

for(int i = 0 ; i < v.size() ; ++i)

You compare i, which is a signed integer, to v.size(), which is of the unsigned type size_t. Replace int by size_t:

for(size_t i = 0 ; i < v.size() ; ++i)
shrike
  • 4,449
  • 2
  • 22
  • 38
0

In the for loop use unsigned instead of int and it will solve the problem. You are comparing i with is signed int with an unsigned v.size().

kemis
  • 4,404
  • 6
  • 27
  • 40
0

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;
}
Community
  • 1
  • 1
Toma Radu-Petrescu
  • 2,152
  • 2
  • 23
  • 57