Converting string to number, stringstream

Hi, first of all excuse my English, please.

This is a part of a code (http://www.cplusplus.com/forum/articles/6046/ - this topic is already archived, so I'm not allowed to reply there...), I don't understand the if statement, I know what it does, but I do not know how it works. What's the principle? Can anybody explain it to me, please?

Thank you very much!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

 string input = "";

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber) // I DON'T UNDERSTAND WHAT'S HAPPENING HERE!
     break;
   cout << "Invalid number, please try again" << endl;
 }
Well, have you ever written cin >> my_int;? The same thing happens here.
cin is a stream and myStream is a stream too. Streams have an overloaded operator >> that extracts data. If >> can't find the thing you looking for (int in this case) it fails.
First at all, the expression
 
myStream >> myNumber

looks into the stream checks if there is a number to get from at front of the input queue and if so, stores into myNumber. But now comes the issue.

myStream >> myNumber can be rewritten into myStream.operator>>(myNumber);, and so it returns the stream ojects itself, since this is the declaration of operator>>.
The if clause want to have boolean to check if its true and false! UhOh! What we have is a std::istream object. (myStream was return from operator>>).
The trick is, that the class std::istream defines a bool operation, means, if you expect myStream to be a bool, it will be converted with the member function good(). In other words. If you do a check on a stream (convert it to bool) it will be false if an error occurs, or true if everything was fine.

Soooooooo

 
if (myStream >> myNumber)  // will be true, if worked, false if error occured. 


what we still have to know is: When does an error occur? It does occur if you expect an integer, (like in your case) but the first chars in your string are no numbers, but some alphabetic chars. In other words, if the Stream cant extract what you wish for, because we cant match in our input any numbers, than myStream will set some error flags and your expression will be evaluated as false!

Ahm... i tipped really a lot. Did you understand or more?
Sorry, my english is not good.

Maikel
to: hamsterman, maikel

thank you, now it is quite clear to me...
Topic archived. No new replies allowed.