This problem was from the book C++ Primer Plus Chapter 4 #8. The point of the code is to create a structure and use the new keyword to dynamically create a new structure. This problem makes me alter my code for the previous problem in the book so that I must enter the diameter before the name. However, getline(cin, p->name) does not work for me for some reason even though it did when I asked for the name before the diameter. It just asks for the diameter and after I enter it, the program asks me for the weight right after. Does anyone know the problem? Thank you!

#include <iostream>

using namespace std;

struct pizza
{
    string name;
    int diameter;
    double weight;
};

int main()
{
  pizza *p = new pizza;
  cout << "Enter diameter: ";
  cin >> p->diameter;
  cout << "Enter name of the company: ";
  getline(cin, p->name);
  cout << "Enter weight: ";
  cin >> p->weight;
  cout << p->name << endl << p->diameter << endl << p->weight << endl;
  return 0;
}

Probably some input left in the stream. There are tutorials for avoiding this. Which is probably the best idea if you want to know what's going on.

Otherwise you can use my method:

int someInt = 0;
cin >> someInt; //<- if the user bunks this up and
//enters say a letter, cin will enter fail state, and there
//will probably be data left in the buffer--which happens in other
//ways also.
//so:
cin.sync();//<-- ignore anything left in the stream.
cin.clear();//<-- clear error bits.

See here for more info: http://www.cplusplus.com/reference/iostream/istream/

This problem makes me alter my code for the previous problem in the book so that I must enter the diameter before the name.

The order that you assign values to the members of a structure shouldn't matter. Are you sure that this is the case?

Also, you could consider using getline(std::cin, line) for all the inputs. For numbers you can do:

std::string tempString;

std::cout << "Enter name: ";
getline(std::cin, p->name);

std::cout << "Enter size: ";
getline(std::cin, tempString);
p->diameter = atoi(tempString.c_str());   // convert to an int

std::cout << "Enter weight: ";
getline(std::cin, tempString);
p->weight = atof(tempString.c_str());     // convert to a float

This method gets rid of the issue with having to clear the input stream all the time.

Nvm, I used cin.sync() and it worked! Thank you!

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.