Search code examples
c++g++stringstream

print sum if all inputs are valid otherwise print "Invalid" in c++


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 

Solution

  • 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)