surprise

S

Stefan Ram

I was surprised by something about a part of the language I
thought I already knew.

Below, you see a program that is supposed to read lines like
»2+3« and sum up the values of each line as shown below for two
sample inputs. However, when the program is tested, the second
result will be false (not »11«). Can you see why?

#include <iostream>
#include <ostream>
#include <string>
#include <sstream>

int main()
{ ::std::string input; while( getline( ::std::cin, input ))
{ ::std::stringstream source; source << input; int sum = 0;
while( getline( source, input, '+' ))sum += ::std::stoi( input );
::std::cout << sum << '\n'; }}

2+3
5
2+9
11
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top