mikey
mikey

Reputation: 1460

cin.Getline returns nothing

I am trying to learn c++. I am on strings now. I have written this simple method that should ask to input a string and then return it. To do so I am using cin.getLine() method but the string is not printed after I use cin.getLine()

string getString(char string[])
{

  cout << "Please enter a string to process ";
  cin >> string;
  cout << "String in getString before process: " << string << "\n";
  cin.getline(string, STRINGSIZE);
  cout << "String after processing: " << string << "\n"; // here string is not printed
  return string;
}

Can anybody help me to understand what I am doing wrong? Thank you

Upvotes: 1

Views: 789

Answers (1)

4pie0
4pie0

Reputation: 29724

you are first reading string to std::string with cin >> string; and then read again something from cin with cin.getline(string, STREAMSIZE); it is not necessary, read it once and return:

string getString(char string[]){
  cout << "Please enter a string to process ";
  cin >> string;
  cout << "String in getString before process: " << string << "\n";
  // process this, do whatever you describe as processing it
  cout << "String after processing: " << string << "\n"; // string is printed
  return string;
 }

otherwise, if you want to use getline, do:

  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name); // or std::getline(std::cin,string, 'r'); to read
  //only to delimiter character 'r'
  std::cout << "Hello, " << name << "!\n";

so thing to remember is use getline OR cin, not both simultaneously unless there is really some special reason

Upvotes: 2

Related Questions