Computer Science Canada

quick question

Author:  Geminias [ 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;
}

Author:  wtd [ Mon Oct 03, 2005 9:20 pm ]
Post 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;
}

Author:  Geminias [ Mon Oct 03, 2005 10:28 pm ]
Post subject: 

thanks wtd !


: