1

我有以下方法,它没有从用户那里捕获任何东西。如果我输入 New Band 作为艺术家姓名,它只会捕获“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 回答