stringstream

Discussion in 'Web Design & Programming' started by zeus, Nov 17, 2006.

  1. zeus

    zeus out of date

    Likes Received:
    0
    Trophy Points:
    36
    Ive been following this tutorial but dont really get the point made in the stringstream section.....
    Basic Input/Output

    Am I right in thinking all the code is doing (right at the bottom of the page) is saving the getline variable as a string called mystr then converting it with stringstream into a numerical variable called price.

    Then the same for quantity.

    Why not just save the numbers as variables and multiply those. I dont get the point in saving it as a string and then turning it into a number.

    But maybe ive got it all wrong!
     
  2. Addis

    Addis The King

    Likes Received:
    91
    Trophy Points:
    48
    I'm not exactly sure why you wouldn't just accept integer only input, instead of messing around with stringstream, but it does have a purpose when a user specified string can be safely and easily converted to another type.

    You'll probably find uses for it later on. Sometimes I use a traditional string with a char array, and then get user input in C++ by using the cin.getline() function.
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    char str[200];
    cin.getline(str, 200);
    cout << str << endl;
    return 0;
    }
    But its up to you how you do it. Sometimes its helpful to have C++ classes like stringstream to do some of the heavy work of checking bounds, and keeping everything safe.
     
  3. zeus

    zeus out of date

    Likes Received:
    0
    Trophy Points:
    36
    Thanks for the reply Addis. I'll keep working through the tutorial and see how it goes.

    Ive got another problem though. Ive only just tried to compile some code (In dev-C++) but I think im doing something wrong.

    Whenever I run my compiled code my DOS window closes just when I expect to see the final output.

    ie
    Code:
    // stringstreams
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    int main ()
    {
      string mystr;
      float price=0;
      int quantity=0;
    
      cout << "Enter price: ";
      getline (cin,mystr);
      stringstream(mystr) >> price;
      cout << "Enter quantity: ";
      getline (cin,mystr);
      stringstream(mystr) >> quantity;
      cout << "Total price: " << price*quantity << endl;
      return 0;
    }
    
    I enter the price, then the quantity. Press enter and it closes.

    When I open Dev-C++ I just go to file, new, source file. Is this correct or is this where im going wrong?
     
  4. zeus

    zeus out of date

    Likes Received:
    0
    Trophy Points:
    36
    It doesnt matter, I just directed DOS to my .exe It stays open now.
     

Share This Page