簡體   English   中英

C ++使用cin執行while循環

[英]C++ do while loop with cin

下面是我用cin做while 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=="");

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

檢查長度,然后檢查@。

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

    do
    {
    ...
    }while(emailAddress.length()<3||emailAddress.find("@")==string::npos);

使用clear()和ignore()函數也可以忽略已存儲在輸入中的單詞

定義一個函數以避免重復代碼:

#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: ");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM