I am trying to learn C++ since yesterday and I am using this document:http://www.cplusplus.com/files/tutorial.pdf (page 32) . I found a code in the document and I ran it. I tried inputting Rs 5.5 for price and an integer for quantity and the output was 0. I tried inputting 5.5 and 6 and the output was correct.
// 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;
}
Question: What exactly does the mystring command do? Quoting from the document:
"In this example, we acquire numeric values from the standard input indirectly. Instead of extracting numeric values directly from the standard input, we get lines from the standard input (cin) into a string object (mystr), and then we extract the integer values from this string into a variable of type int (quantity)."
My impression was that the function will take the integral part of a string and use that as input.
(I don't exactly know how to ask a question here. I am also new to programming) Thank you.
See Question&Answers more detail:os