1

下面是我用 cin 做的 while 循环 有一点问题,当用户输入全名然后按回车。指针将转到下一行。直到用户再次按回车键,然后它提示电子邮件地址,我如何在下面的代码中输入全名后立即提示电子邮件地址

终端外观:

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=="");
4

4 回答 4

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=="");
于 2012-08-20T19:38:43.693 回答
1

检查长度,然后@。

 do
    {
    ...
    }while(fullname.length()<2);

    do
    {
    ...
    }while(emailAddress.length()<3||emailAddress.find("@")==string::npos);
于 2012-08-20T19:46:55.963 回答
0

也使用 clear() 和 ignore() 函数来忽略已经存储在输入中的单词

于 2012-08-20T19:36:07.707 回答
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: ");
}
于 2012-08-20T20:04:37.590 回答