Tom Rogers
Tom Rogers

Reputation: 3

C++ Menu Ordering System won't accept multiple words when inputting to the txt file

My code below, whenever I input the menu items, will automatically end the program if I add more than one word such as "Tequila Sunrise" rather than "Tequila". How do I fix this to make it so I can add items with more than one word in the name?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    // Restaurant Side Title
    cout << "Welcome to the Menu Ordering System. \n\n\n";

    // Create a txt file to store the menu
    fstream MenuWriteFile("drinksmenu.txt");
    fstream MenuPricesFile ("drinksprices.txt");
    
    // Write the menu to the file
    string myDrinks;
    double drinksPrices;
    int i;
    cout << "Please enter your first drink: ";
    cin >> myDrinks;
    MenuWriteFile << myDrinks << endl;
    cout << "Price: ";
    cin >> drinksPrices;
    MenuPricesFile << drinksPrices << endl;
    cout << "To add another drink type 1, if not type 0: ";
    cin >> i;
    while (i == 1) {
        cout << "Please enter your next drink: ";
        cin >> myDrinks;
        MenuWriteFile << myDrinks << endl;
        cout << "Price: ";
        cin >> drinksPrices;
        MenuPricesFile << drinksPrices << endl;
        cout << "To add another drink type 1, if not type 0: ";
        cin >> i;
    }
    
    MenuWriteFile.close();
    MenuPricesFile.close();
    
    // Create a text string, which is used to output the text file
     string myText;

     // Read from the text file
     ifstream MenuReadFile("drinksmenu.txt");

     while (getline (MenuReadFile, myText)) {
       cout << "\n\n" << myText << "\n";
     }

     // Close the file
     MenuReadFile.close();
    return 0;
    }

Upvotes: 0

Views: 246

Answers (1)

David G
David G

Reputation: 96800

Use std::getline():

while (i == 1) {
  cout << "Please enter your next drink: ";
  std::getline(std::cin >> std::ws, myDrinks);
  ....

Upvotes: 1

Related Questions