Click here to Skip to main content
15,909,602 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am quite new to C++ and I am trying to create console application with inputs:


C++
int _tmain(int argc, _TCHAR* argv[])
{
	std::string Server, UserName, Password;
	int Port=0;
	
	////////////		GET SERVER NAME     ////////////////////
	cout << "\n\n\n\nPlease enter Server name or IP: ";
	getline (cin, Server);
	if (Server.length()==0) goto exit;
	bool hasSpace =false; int i=0;
	while( i < Server.length())  {
		if(Server[i++] == ' ') hasSpace = true;  //whatever 
	}
	if (hasSpace)
	{
		cout << "\nError: Server name cannot contain spaces!\n\n";
		goto wait_exit;
	}


	////////////		GET PORT NUMBER     ////////////////////
	cout << "\nServer Port number: ";
	cin >> Port;
	if (Port==0) goto exit;
	if (Port <0)
	{
		cout << "\nError: Port number cannot be negative!\n\n";
		goto wait_exit;
	}
	if (Port >99000)
	{
		cout << "\nError: Port number cannot out of range! Maximum port number 99000.\n\n";
		goto wait_exit;
	}
	
	////////////		GET USER NAME     ////////////////////
	cout << "\n\n\n\nPlease enter User name: ";
	getline (cin, UserName); //misses this
	if (UserName.length()==0) goto exit;


//does not come to here

wait_exit:
	printf("\n");
	system("pause");
exit:
	return 0;


the code works and requests to type in server name, then port number, but its jumps over Username line
getline (cin, UserName);
without waiting for input.

What am I doing wrong here?
Posted

This [^] should answer your question. Hint: The problem is
cin >> Port;
 
Share this answer
 
It's not a good idea to mix the >> operator with getline() calls. They can be considered incompatible, reason being... one reads until the newline character is reached (or carriage return) and the other fails to remove the newline character from a stream after it has just read something.

I'm sure you can figure out which does what based on your bug.
 
Share this answer
 
Adding lines after port input:

C++
cin.clear();
cin.ignore(1000,'\n');


resolved my issue
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900