Need Help about code confusion

Hi, I had a question about the following code from the website. My question was that why do we use the first complex code and not the simpler code, number 2 below. What is the point? Could you also explain why float price and int quantity are set to zero. And another question, I had is that why does the program disappear(number 2) right after displaying the result, it stays if I use the site but vanishes when I use c++ on my computer. This happens with all my programs which contain cin often even after using cin.get() and return 0. Thanks.

1) Complex Code

#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;
cin.get();
return 0;
}


2) Much simpler code

#include <iostream>
using namespace std;

int main()
{
float price;
int quantity;

cout << "Enter price: ";
cin >> price;

cout << "Enter quantity: ";
cin >> quantity;

cout << "Total price: " << price*quantity << endl;
cin.get();
return 0;
}
Last edited on
getline() is just an embedded function. It has it's uses. but really works the same.
you'll find multiple ways to do anything.

if you want to display the results so you can see them... under the debug tab there are two options "start without debugging" and "start debugging" you want the Ctrl+f5 to see the results.

setting variables to zero is important for initialization. maybe google initialization. .. but the important thing is to start whatever your computing from a specified value, zero is a good place to start.
Topic archived. No new replies allowed.