I have the following method which is not capturing anything from the user.If I input New Band for the artist name, it only captures "New" a开发者_高级运维nd it lefts out "Band". If I use cin.getline() instead nothing is captured. Any ideas how to fix this?
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;
}
This worked just fine. Thank you Roger
std::string getArtist()
{
cout << "Enter Artist of CD: " << endl;
while(true){
if ( getline(cin, artist)){
}
cout << "artist is " << artist << '\n';
}
return artist;
}
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");
}
}
}
The whole thing is a general improvement, but the use of getline is possibly the most significant for your question.
void example_use() {
std::string artist = getArtist();
//...
// it's really that simple: no allocations to worry about, etc.
}
This is the specified behaviour; istream
s only read up to a space or a newline. If you want an entire line, you use the getline
method, as you already discovered.
Also, please use std::string
instead of char*
in any new C++ code, unless there are very good reasons otherwise. In this case, it will save you from all kinds of problems like buffer overflows, without any extra effort on your part.
If you're going to have white space separators in your input, you need to use getline for your input. That would make your ignore unnecessary.
精彩评论