1

ユーザーから何もキャプチャしない次の方法があります。アーティスト名にNewBandを入力すると、「New」のみがキャプチャされ、「Band」は省略されます。代わりにcin.getline()を使用すると、何もキャプチャされません。これを修正する方法はありますか?

char* artist = new char [256];

char * getArtist()
{
    cout << "Enter Artist of CD: " << endl;
    cin >> artist;      
    cin.ignore(1000, '\n');
    cout << "artist is " << artist << endl;
    return artist;
}

これはうまくいきました。ありがとうロジャー

std::string getArtist()

{   

    cout << "Enter Artist of CD: " << endl;

    while(true){            

        if ( getline(cin, artist)){

        }

    cout << "artist is " << artist << '\n';

    }

    return artist;

}
4

3 に答える 3

2
std::string getArtist() {
  using namespace std;
  while (true) {
    cout << "Enter Artist of CD: " << endl;
    string artist;
    if (getline(cin, artist)) {             // <-- pay attention to this line
      if (artist.empty()) { // if desired
        cout << "try again\n";
        continue;
      }
      cout << "artist is " << artist << '\n';
      return artist;
    }
    else if (cin.eof()) { // failed due to eof
      // notice this is checked only *after* the
      // stream is (in the above if condition)

      // handle error, probably throw exception
      throw runtime_error("unexpected input error");
    }
  }
}

すべてが一般的な改善ですが、getlineの使用はおそらくあなたの質問にとって最も重要です。

void example_use() {
  std::string artist = getArtist();
  //...

  // it's really that simple: no allocations to worry about, etc.
}
于 2010-03-20T23:02:22.190 に答える
1

これは指定された動作です。istreams は、スペースまたは改行までしか読み取れません。行全体が必要な場合は、getline既に発見した方法を使用します。

また、よほどの理由がない限り、新しい C++ コードではstd::string代わりに使用してください。char*この場合、余分な努力をしなくても、バッファ オーバーフローなどのあらゆる種類の問題からあなたを救うことができます。

于 2010-03-20T23:03:28.360 に答える
0

入力に空白区切りを含める場合は、入力にgetlineを使用する必要があります。それはあなたの無視を不必要にします。

于 2010-03-20T23:07:16.517 に答える