1
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else 
{
    system("cls");
    cout << "Your message has to be between 1 and 500 characters long...";
    goto prot;
}

したがって、このコードに到達するたびに、自動的にリターンが押され、getline() 関数が「スキップ」されます (別名、protラベルに移動します)。何故か同じことがさらに上に起こる。ただし、少し実験した後、これを使用すると次のことがわかりました。

input:
if (special == 0)
{
    cout << "Choose your input message below:\n";
    getline(cin, inp);
    if (inp.length() > 0 && inp.length() < 500) {}
    else 
    {
        system("cls");
        cout << "Your message needs to be between 1 and 500 characters long\n";
        goto input;
    }
}

2回目(つまり、inputラベルに行った後)に機能します。これら 2 つのコードの違いは、最初のコードはstd::cinに戻る前にコードをバイパスする必要getline()があるのに対し、もう 1 つのコードはバイパスしないことです。
解決策といくつかの説明をいただければ幸いです。

4

1 に答える 1

0

以下は私にとってはうまくいきます:

#include <iostream>
#include <string>

int main() {
  std::string str;
start:
  std::cout << "prompt:\n";
  std::getline(std::cin, str);
  if (0 < str.length() && str.length() < 20) {}
  else {
    std::cout << "invalid.\n";
    goto start;
  }
  std::cout << "input: \"" << str << "\"\n";
}

あなたのものはこれとどう違うのですか?

于 2013-11-01T13:30:14.953 に答える