下面是我用cin做的while循环 有一点问题,当用户输入Fullname然后按回车键。 指针将转到下一行。 直到用户再次按回车键,然后提示电子邮件地址,如何在我的代码下面输入全名后立即提示电子邮件地址
终端看:
Full Name: John
Email Address: some_email@gmail.com
我的test.cpp代码:
emailAddress= "";
fullname = "";
counter = 0;
if(department_selection!="")
{
while(fullname=="")
{
if(counter>0)
{
//so it wont print twice
cout << "Full Name: ";
}
getline(cin,fullname);
cin.clear();
cin.ignore();
counter++;
}
counter = 0;
while(emailAddress=="")
{
if(counter>0)
{
//so it wont print twice
cout << "Email Address: ";
}
getline(cin,emailAddress);
cin.clear();
cin.ignore();
counter++;
}
}// if department selection not blank
还是同样的问题。我需要输入一次,然后提示输入电子邮件地址。
最新更新:管理以解决此问题。我对代码进行了更改,它是这个版本:
do
{
if(counter==0)
{
//so it wont print twice
cout << "Full Name: ";
}
if(counter>1)
{
//so it wont print twice
cout << "Full Name: ";
}
getline(cin,fullname);
counter++;
} while (fullname=="");
counter = 0;
do
{
if(counter==0)
{
//so it wont print twice
cout << "Email Address: ";
}
if(counter>1)
{
cout << "Email Address: ";
}
getline(cin,emailAddress);
counter++;
} while (emailAddress=="");
答案 0 :(得分:2)
而不是if(counter>0)
使用if(counter==0)
我的工作测试应用:
int counter = 0;
string fullname, emailAddress;
do
{
if(counter==0)
{
//so it wont print twice
cout << "Full Name: ";
}
getline(cin,fullname);
counter++;
} while (fullname=="");
counter = 0;
do
{
if(counter==0)
{
//so it wont print twice
cout << "Email Address: ";
}
getline(cin,emailAddress);
counter++;
} while (emailAddress=="");
答案 1 :(得分:1)
检查长度,然后检查@。
do
{
...
}while(fullname.length()<2);
do
{
...
}while(emailAddress.length()<3||emailAddress.find("@")==string::npos);
答案 2 :(得分:0)
使用clear()和ignore()函数也可以忽略已经存储在输入中的单词
答案 3 :(得分:0)
定义一个函数以避免重复代码:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
string get_input(const std::string& prompt)
{
string temp;
cout << prompt;
while (!getline(cin, temp) || temp.empty()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return temp;
}
int main()
{
string fullname = get_input("Full Name: ");
string email = get_input("Email Adress: ");
}