need some explanation of stringstream()

I am new to C++ ( I only know a little bit of python, so, I am fairly new to programming as well )
I don't understand the' while(!stringstream(swap) >> width)' part
(in a a program that asks the user to type the width and the height of a rectangle and then outputs to the screen the area and the perimeter of that rectangle)
Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <sstream>
using namespace std;
 
int main()
{
  string swap;
 
  cout << "Input the width of the rectangle: ";
  double width;
  cin >> swap;
  while ( !(stringstream(swap) >> width) )
  {
    cout << "Error! Type mismatch! \nInput again: ";
    cin >> swap;
  }
 
  cout << "Input the height of the regtangle: ";
  double height;
  cin >> swap;
  while ( !(stringstream(swap) >> height) )
  {
    cout << "Error! Type mismatch! \nInput again: ";
    cin >> swap;
  }
 
  cout << "The area of the rectangle is " << height * width << endl;
  cout << "The perimiter of the rectangle is " << 2 * (height + width) << endl;
return 0;
}
> while ( !(stringstream(swap) >> width) )

favour using an input string stream for this: while ( !( std::istringstream(swap) >> width) )

stringstream(swap) - anonymous object of type stringstream that reads from (a copy of) the string swap

stringstream(swap) >> width - attempt to read a floating point value into width.
If the attempt was successful, the value read would be placed into width and the stream would be in a good state.
If not (could not read a floating point value), the stream would be in a failed state

!(stringstream(swap) >> width) - true, if the stream is in a failed state
ie. if the attempt to read a floating point value failed

while ( !(stringstream(swap) >> width) ) - while( the attempt to read a floating point value from the characters in the string swap failed )
Last edited on
Thanks !
Topic archived. No new replies allowed.