Read a string from keyboard and decide if to exit a while loop : string read « string « C++ Tutorial






#include <iostream>
#include <string>

using namespace std;

class Product
{
public:
   Product();

   void read();

   bool is_better_than(Product b) const;

   void print() const;
private:
   string name;
   double price;
   int score;
};

Product::Product()
{  
   price = 1;
   score = 0;
}

void Product::read()
{  
   cout << "Please enter the model name: ";
   getline(cin, name);
   cout << "Please enter the price: ";
   cin >> price;
   cout << "Please enter the score: ";
   cin >> score;
   string remainder; /* read remainder of line */
   getline(cin, remainder);
}

bool Product::is_better_than(Product b) const
{  
   if (b.price == 0) return false;
   if (price == 0) return true;
   return score / price > b.score / b.price;
}

void Product::print() const
{  
   cout << name
      << " Price: " << price
      << " Score: " << score << "\n";
}

int main()
{  
   Product best;

   bool more = true;
   while (more)
   {  
      Product next;
      next.read();
      if (next.is_better_than(best)) best = next;

      cout << "More data? (y/n) ";
      string answer;
      getline(cin, answer);
      if (answer != "y") more = false;
   }

   cout << "The best value is ";
   best.print();

   return 0;
}








15.15.string read
15.15.1.Use cin in while loop to read string
15.15.2.Read a string from keyboard and decide if to exit a while loop
15.15.3.Use cin to read string
15.15.4.Read string till a sign
15.15.5.Read string from keyboard and get substring