1

以下は、cin を使用した私の do while ループです。ユーザーが Fullname を入力して Enter キーを押すと、少し問題が発生します。ポインタは次の行に移動します。ユーザーがもう一度Enterキーを押すまで、電子メールアドレスが表示されます。以下のコードにフルネームを入力した直後に電子メールアドレスを表示するにはどうすればよいですか

端末の外観:

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

コードの繰り返しを避ける関数を定義します。

#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 に答える
0

clear() 関数と ignore() 関数を使用して、入力に既に格納されている単語を無視します

于 2012-08-20T19:36:07.707 に答える