why i have to press "enter" twice before getline can read the string... can anybody help me to solve this problem...

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

int main() {
	
	string *name, hold;
	int num, i, j;
	
	cout << "----------------------------------------------------\n"
		 << "This program creates a dynamic student record system\n"
		 << "----------------------------------------------------\n";

	cout << "\nPlease enter the numbers of student: ";
	cin >> num;

	name = new string [num];

	cout << "\n";
	
	for ( i = 0; i < num; i++ ) {
		
		cout << "Please enter the name of student [" << i + 1 << "]: ";
		fflush(stdin);
		getline( cin, name[i] ); 
		
		cout << name[i];

		for ( j = 0; j <= i; j++ )
			if ( name[i] < name[j] ) {
				hold = name[i];
				name[i] = name[j];
				name[j] = hold;
			}

	}

	cout << "\nList of student <sorted>:\n";

	for ( i = 0; i < num; i++ )
		cout << name[i] << endl;

	cout << "\nList of student name that contains the string Mo:\n";
	
	for ( i = 0; i < num; i++ )
		if ( name[i].find( "Mo" ) == 0 )
			cout << name[i] << endl;

	cout << "\n";

	delete [] name;
	
	return 0;
}

Recommended Answers

All 2 Replies

Works for me..you just might want to put

cout << name[i];
cout << endl;

so that the name appears on its own line..makes it easier to read.

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.