I'm working with structures, but somehow it skips one of the user inputs for the pie's price:

#include <iostream>
#include <windows.h>
#include <string>
#include <conio.h>

using namespace std;

const int ESC = 0x1b; 

struct pie{
       string brand;
       float price;
       string flavour;
}pies[5];

int main()
{
    cout << "Structures.";
    cout << "\nPress c to contine.";
    int a;
    while ( (a = getch()) != ESC)
    if (a == 'c')
    {
          int n;
          int g;
          for (n = 0; n<5; n++)
          {
              cout << "\nEnter brand of pie:";
              getline(cin,pies[n].brand);
              cout << "\nEnter price of pie:";
              cin >> g;
              pies[n].price = g;
              cout << "\nEnter Flavour of pie:";
              getline(cin,pies[n].flavour);
          }
          getch();
          return 0;
    }
}

When I get up to Enter brand of pie, then I press enter, it skips straight onto Enter Flavour of pie leaving the price of pie blank. I've tried cin.ignore() but that doesn't seem to do it. Any help would be appreciated.:-/

There's plenty of ways around the many problems associated with cin >> ; IMHO the best way to avoid them is to never use the >> operator in conjunction with cin in the first place (unless its really necessary).

My personal preference is to keep a separate function which grabs a line using getline(), and a stringstream to convert your input to whatever numeric type you need.

bool read_float( std::istream& in , float& num )
{
    std::string str;
    std::getline( in, str );
    std::istringstream iss( str );
    iss >> num;
    return iss.good();
}

This has the added bonus of removing the risk that cin will fail due to invalid chars being typed. You can check for this after asking the user to enter the price of the pie.

cout << "\nEnter price of pie:";
while ( ! read_float( std::cin , g ) ) 
    std::cout << "Invalid input - Enter price of pie: ";

One slight nitpick - the default floating-point type in C++ is double. For that reason its usually recommended to always use double whenever you need floating point numbers, unless you have some compelling reason otherwise to use float (which generally suffers from low precision. usually only 5 or 6 s.f. on most modern machines)


edit if you want to be extra-clever you can template the 'read' function to work with other numeric types (which would be handy if you wanted to do the same with int or double)

template <typename Ty>
bool read_in( std::istream& in , Ty& num )
{
    std::string str;
    std::getline( in, str );
    std::istringstream iss( str );
    iss >> num;
    return iss.good();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.