abdu
abdu

Reputation: 103

Extract a value from an input of type string and assign to a variable

I have a very basic question. It's about extracting a value from a string input and then assigning this value to an int and then copying out this integer to screen. Here is my code:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
    string mystr;
    float price;
    int quantity;
    cout << "What is your name? ";
    getline (cin,mystr);
    cout << "Hello Mr. " << mystr << endl;
    cout << "Enter price: ";
    getline (cin,mystr);
    stringstream(mystr) >> price;
    cout << "Enter quantity: ";
    getline (cin,mystr);
    stringstream (mystr) >> quantity;
    cout << "Total price: " << quantity*price << endl;
    cout << "Thank you for purchasing our product!";
    return 0;
}

So the question is: when asked to enter price. Can I type "Price is 16" for example and the program is supposed to extract the 16 from the input and assign it to price?

Upvotes: 0

Views: 742

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596332

If you allow that type of input, you would have to strip off the Price is portion before you can then read the 16 portion. Easiest way to do that is to simply put the input into a stringstream and call its >> operator in a loop until you reach a number or the end of the stream, eg:

cout << "Enter price: ";
getline(cin, mystr);

stringstream ss(mystr);
do
{
    if (ss >> price)
        break;
}
while (!ss.eof());

if (!ss)
{
    // no price provided, do something...
}

Upvotes: 1

Related Questions