Getting user input in C++

39,896

Formatted I/O; taken from Baby's First C++:

#include <string>
#include <iostream>

int main()
{
  std::string name;
  std::cout << "Enter your name: ";
  std::getline(std::cin, name);
  std::cout << "Thank you, '" << name << "'." << std::endl;
}

This isn't quite satisfactory, as many things can (and thus will) go wrong. Here's a slightly more watertight version:

int main()
{
  std::string name;
  int score = 0;

  std::cout << "Enter your name: ";

  if (!std::getline(std::cin, name)) { /* I/O error! */ return -1; }

  if (!name.empty()) {
    std::cout << "Thank you, '" << name << "', you passed the test." << std::endl;
    ++score;
  } else {
    std::cout << "You fail." << std::endl;
    --score;
  }
}

Using getline() means that you might read an empty line, so it's worthwhile checking if the result is empty. It's also good to check for the correct execution of the read operation, as the user may pipe an empty file into stdin, for instance (in general, never assume that any particular circumstances exist and be prepared for anything). The alternative is token extraction, std::cin >> name, which only reads one word at a time and treats newlines like any other whitespace.

Share:
39,896
melonQheadQsheep
Author by

melonQheadQsheep

Updated on July 09, 2022

Comments

  • melonQheadQsheep
    melonQheadQsheep almost 2 years

    I am writing a program that allows a student to write a question and store that Question (or string) in a variable, can anyone please tell me the best way to get user input

    thanks for your answers and comments

    • Mat
      Mat over 12 years
      Did you look at any of the related questions you got while writing this? Did you look at the questions linked in the "related" section on the right of this very page?
    • melonQheadQsheep
      melonQheadQsheep over 12 years
      I could use: string str = ""; getline(cin, str, '\n'); is this a good way of collecting input and using in a multithreading program
    • JFreeman
      JFreeman almost 3 years
  • Cool_Coder
    Cool_Coder over 12 years
    @KerrekSB why do u think so???
  • Kerrek SB
    Kerrek SB over 12 years
    Hey, where did my comment go?? On topic, gets() is dangerous because it's entirely unchecked, and it is widely deprecated and discouraged. Definitely not something one should recommend, even less so in the context of C++.