tags:

views:

150

answers:

3

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" and 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;

}
+2  A: 
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.
}
Roger Pate
This works fine except that everytime I get "try again". Any ideas how to fix that?
@user: As written above, that will only happen if the input is empty (the user pressed enter at the prompt without typing anything). Perhaps you miscopied it?
Roger Pate
+1  A: 

This is the specified behaviour; istreams 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.

calmh
A: 

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.

JadziaMD