Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

sstream basics

Posted on 2004-04-01
13
Medium Priority
?
823 Views
Last Modified: 2009-07-29
I want to convert a string of digits (may include +,-,.) to a double using sstream. plz give a good general example. so far I have found that I can convert the string to a buffer (I don't know how I can do that) and read from that buffer into a double.

thx Xperts
J
0
Comment
Question by:jhshukla
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 2
13 Comments
 
LVL 10

Assisted Solution

by:Sys_Prog
Sys_Prog earned 75 total points
ID: 10738766
Have a look at this code

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

using namespace std ;

int main(int argc, char* argv[])
{
      string test ( "123.543  162.124 542 123.134" ) ;
      stringstream str ( test ) ;
      double d1, d2, d3 ;
      int i, j ;
      
      str >> d1 ;
      cout << "D1 : " << d1 << endl ;
      str >> d2 ;
      cout << "D2 : " << d2 << endl ;
      str >> i ;
      cout << "i : " << i << endl ;      

      str >> j ;
      cout << "j : " << j << endl ;      
      str >> d3 ;
      cout << "D3 : " << d3 << endl ;
       
       
      system("pause");
      return 0;
}


Amit
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10738781
This should give you a kick start...
--------8<--------
#include <iostream>
#include <sstream>

int main()
{
        std::string str = "-39.76 8.76e-99";
        std::istringstream istr(str);
        double d;
        while (istr >> d)
                std::cout << "Here's a double " << d << '\n';
}
--------8<--------
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10738784
[Sorry Amit got there first!]
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:Sys_Prog
ID: 10738792
No probs  rstaveley, happens quite a lot at EE

Amit
0
 
LVL 9

Author Comment

by:jhshukla
ID: 10741026
perfect! now you guys can clear a few doubts --
is it possible to add some more text to the stringstream after starting to extract from it? if yes where will the text be placed - at index 0 or at the end?

is there a way to extract the whole buffer NOT using [[[> s_stream >> some_string_variable <]]]?

plz also look at two peices of code below and corresponding output on VC++6.0

thx
J

EXAMPLE 1
=======
#include <sstream>
#include <iostream>
#include <string>

using namespace std;

int main(){
      string s = "345.89 23.9 3e-6 4";
      stringstream str(s);
      double d; int i;
      for(i=0; i<4; i++){
            str >> d;
            cout << d << endl;
      }
      return 0;
}
OUTPUT 1
------------
345.89
23.9
3e-006
4

EXAMPLE 2
=======
#include <sstream>
#include <iostream>
#include <string>

using namespace std;

int main(){
      string s = "345.89 23.9 3e-6 4";
      stringstream str(s);
      str << " 56.7";
      double d; int i;
      for(i=0; i<5; i++){
            str >> d;
            cout << d << endl;
      }
      return 0;
}
OUTPUT 2
------------
56.79
23.9
3e-006
4
4
:::::::::::::::::
 end of output
:::::::::::::::::
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10741938
You can get it to work bidirectionally, provided you don't use the std::string constructor.

i.e. This works:
--------8<--------
#include <iostream>
#include <sstream>
#include <string>

int main()
{
      std::stringstream sstr;
      sstr << "the rapist Mr physio";
            // Don't use constructor for this
            // otherwise you get an istringstream

      std::string str;
      for (int i = 0;i < 2;i++) {
            sstr >> str;
            sstr << str;
      }

      while (sstr >> str)
            std::cout << ' ' << str;
      std::cout << '\n';
}
--------8<--------

This doesn't work, because it constructs an istringstream:

      std::stringstream sstr("the rapist Mr physio");
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10741949
NB: If there's any danger of emptying the stringstream after an extraction, you should call sstr.clear() to clear the flags before inserting.
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10741981
You fix the error in EXAMPLE 2, by doing the following:

--------8<--------
    for(i=0; i<5; i++){
          if (str >> d)
              cout << d << endl;
     }
--------8<--------

There are only four tokens, but you attempt to extract 5. The fifth token fails, because you are EOF, but you are not testing the result of the extraction. You therefore see the 4th token twice.
0
 
LVL 9

Author Comment

by:jhshukla
ID: 10755058
thanks, i got that. but one part of the question is still unanswered.
 )= is there a way to extract the entire buffer NOT using [[[> s_stream >> some_string_variable <]]]?

0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10755782
Yes, use sstr.str(). It rturns the contents of the buffer in a std::string.

See http://www.cplusplus.com/ref/iostream/stringstream/str.html
0
 
LVL 9

Author Comment

by:jhshukla
ID: 10808781
how do I get errorflags or exception when I extract a number from sstream and it fails. eg

stringstream str("b456");
double d;
str >>d; // error! how do I catch it?
0
 
LVL 17

Accepted Solution

by:
rstaveley earned 150 total points
ID: 10830938
Sorry about the late response, I've just got back from holiday.

if (!(str >>d))
   throw YourException();
0
 
LVL 9

Author Comment

by:jhshukla
ID: 10855340
Amit, plz don't be pissed off. I gave more points to rstaveley 'coz of his/her continued response.
thx both of u.
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question