控制台应用程序输入帮助
问题描述:
我是C ++的新手,我正在尝试使用输入创建控制台应用程序:
Hi,
I am quite new to C++ and I am trying to create console application with inputs:
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?
答
此[ ^ ]应该回答您的问题.提示:问题是
This [^] should answer your question. Hint: The problem is
cin >> Port;
将>>
运算符与getline()
调用混合使用不是一个好主意.它们可以被认为是不兼容的,原因是...一个读取直到到达换行符(或回车),而另一个在读取内容后无法从流中删除换行符.
我确定您可以根据自己的错误弄清楚该做什么.
It''s not a good idea to mix the>>
operator withgetline()
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.
在端口输入后添加行:
Adding lines after port input:
cin.clear();
cin.ignore(1000,'\n');
解决了我的问题
resolved my issue