Nested Structures HELP

So in the code for my assignment I have to collect phone numbers, I know how to do the phone numbers but I'm having a tough time entering a name.
For example run the code and enter 1 for 1 student and it will skip the name input and display. Please what am I doing wrong.


--------------------------

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>

using namespace std;
int Number_Of_Students;

struct Phone{
int area_code;
int prefix;
int suffix;
};

struct StudentPhoneRecord{
string name;
Phone home;
Phone emergency;
Phone peronal_doctor;
};

StudentPhoneRecord student [50];

void Set_Students()
{
cout << "Number of students (must be a positive number less than or equal to 50) = ? ";
cin >> Number_Of_Students;
while (Number_Of_Students > 51)
{cout << "50 Students or less! Please try again"<<endl;
cin >>Number_Of_Students;}
}

void Gather_Numbers()
{
for(int x = 1; x <= Number_Of_Students; x++)
{
cout << "Please enter the information for student "<< x<<"."<<endl;
cout << endl;
cout <<"Name: ";
getline(cin, student[x].name);
}
}

void Display_Data()
{
for(int x = 1; x <= Number_Of_Students; x++)
{
cout << student[x].name << endl;
}
}

int main() {
Set_Students();
Gather_Numbers();
Display_Data();
}
The problem is a classic one of mixing cin >> and getline( cin, std::string )

cin >> leaves the newline character '\n' in the stream ... and this will be picked up as a blank by the following getline().
getline() extracts (and throws away) the newline character.


There are lots of ways round this; here are four of them

(1) Don't mix them: use getline for everything. e.g.
1
2
3
#include <sstream>
string dummy;
getline( cin, dummy );   stringstream( dummy ) >> Number_Of_Students;



(2) After any use of cin >> use cin.ignore to extract up to the newline character (1000 ought to be more than enough):
cin >> Number_Of_Students; cin.ignore( 1000, '\n' );


(3) After any use of cin >> use a getline with a redundant string just to pick up any trailing blanks and the newline:
1
2
string dummy;
cin >> Number_Of_Students;   getline( cin, dummy );



(4) Clear any preceding whitespace at the following getline call:
getline(cin >> ws, student[x].name);
(This is slightly dangerous as it is not local to the problem - you might decide to rearrange your input.)


Take your pick. There are probably plenty more ways of solving the problem. Method (2) seems to be the most used in this forum, but I've used all of them at one time or another.


BTW, your questions would be much easier to answer if you used code tags (first item in the format menu - you can edit a post if it doesn't appear on the initial posting.)

Also, your title doesn't have much to do with the problem.
Last edited on
Registered users can post here. Sign in or register to post.