0

I need a function to get a string input from the user. I don't want to to use cin because I only want return (\r) to mark the end of input. I've done the following:

std::string GetInput()
{
  std::string str = "\0";
  char ch;
  do
  {
    ch = getch();
    if(ch) str += ch;
    putch(ch);
  }
  while (ch!='\r');
  return str;
}

It works but I'm not quite satisfied with it as it doesn't fully support Backspace and Right/Left Arrow keyboard buttons. My question is, how can I get input from the user, without the use of cin, while giving the user a cin-like feeling (full keyboard support)?

2
  • Do you need this particular function or do you just want to get user input? If second, consider using getline, cin and so on. Commented Jun 1, 2013 at 8:33
  • @cdshines Thanks. I didn't know I could use getline to do that. Commented Jun 1, 2013 at 8:52

1 Answer 1

2

You can in fact use cin:

std::string GetInput()
{
  std::string input;
  if (!std::getline(cin, input)) {
    // handle error here
  }
  return input;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thanks! Is there a way to separate the getline and if lines? (to call getline first and then check if it is not empty?) I tried if(input) after calling getline but got an error message saying I can't convert input to a boolean value.
if (input.empty()) { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.