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