Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 quick question
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Geminias




PostPosted: Mon Oct 03, 2005 3:59 pm   Post subject: quick question

is "cin.getline" deprecated? (like is it old and unnecessary?)

Quote:
// cin and ato* functions
#include <iostream>
#include <stdlib.h>
using namespace std;

int main ()
{
char mybuffer [100];
float price;
int quantity;
cout << "Enter price: ";
cin.getline (mybuffer,100);
price = atof (mybuffer);
cout << "Enter quantity: ";
cin.getline (mybuffer,100);
quantity = atoi (mybuffer);
cout << "Total price: " << price*quantity;
return 0;
}
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Mon Oct 03, 2005 9:20 pm   Post subject: (No subject)

Do not use std::string::getline, atof, and character arrays. These make your program very brittle, since they do a poor job of dealing with input that's not exactly what you expect.

Thus we use a std::string which is not limited to 99 characters, as the character array is.

Just as we use the std::cin stream to get input from the keyboard, we can use a stringstream to get input from a string with equal power.

c++:
#include <iostream>
#include <sstream>

int main ()
{
   std::string buffer;
   std::stringstream input_stream;
   float price;
   int quantity;

   std::cout << "Enter price: ";
   std::cout.flush();
   std::getline(std::cin, buffer);
   input_stream = std::stringstream(buffer);

   buffer >> price;

   std::cout << "Enter quantity: ";
   std::cout.flush();
   std::getline(std::cin, buffer);
   input_stream = std::stringstream(buffer);

   buffer >> quantity;

   std::cout << "Total price: " << price * quantity
             << std::endl;

   return 0;
}
Geminias




PostPosted: Mon Oct 03, 2005 10:28 pm   Post subject: (No subject)

thanks wtd !
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: