C++ 用 cin 做 while 循环

标签 c++

下面是我用 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

还是一样的问题。我需要按一次 Tab Enter,然后它会提示输入电子邮件地址。

最新更新:设法修复它。我修改了代码,是这个版本:

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

最佳答案

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

关于C++ 用 cin 做 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043940/

相关文章:

c++ - 变量改变应该不受影响(内存溢出?)

c++ - 访问 IDWriteTextFormat 而不是创建新的(FW1FontWrapper 行间距)

c++ - 将十六进制键值转换为十进制键值

c++ - #include <crtdll/stddef.h> 是什么意思?

c++ - 在 Linux 中调试 C++

c++ - "set_unexpected"在VC2010中不起作用?

C++ 错误 : Type Name is Not Allowed

c++ - 如何在 VS C++ 中使用 IA32 指令 'fabs'?

c++ - 加载 DLL 是否会动态协调其 stderr 到主应用程序?如果是这样,那么如何......?

c++ - C++ 中的通用 ostream 问题