|
|
#1 (permalink) Top |
|
out of date
![]() Join Date: May 2003
Age: 27 Male
Posts: 1,654
Times Helpful: 105
My Mood: Twisted
Status: Offline
|
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 (permalink) Top |
|
The King
![]() ![]() Join Date: Jan 2004
Age: 18 Male
Posts: 5,255
Times Helpful: 403
My Mood: Drunk
Status: Offline
|
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;
}
__________________
Never trust a program you don't have the source code for. ![]() My website | Powerful Desktop Linux | Linux for human beings | Linux for power users | Linux for ricers |
|
|
|
|
#3 (permalink) Top |
|
out of date
![]() Join Date: May 2003
Age: 27 Male
Posts: 1,654
Times Helpful: 105
My Mood: Twisted
Status: Offline
|
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;
}
When I open Dev-C++ I just go to file, new, source file. Is this correct or is this where im going wrong? |
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
|
|