1

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

melonQheadQsheep
  • 121
  • 1
  • 1
  • 6
  • 8
    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? – Mat Oct 30 '11 at 12:25
  • I could use: string str = ""; getline(cin, str, '\n'); is this a good way of collecting input and using in a multithreading program – melonQheadQsheep Oct 30 '11 at 12:32
  • Here's a helpful link for more info https://stackoverflow.com/questions/21257544/c-wait-for-user-input – JFreeman May 28 '21 at 00:44

2 Answers2

15

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

use gets() as this sample example shows. it is short & simple with minimum errors.

Cool_Coder
  • 4,888
  • 16
  • 57
  • 99
  • @KerrekSB why do u think so??? – Cool_Coder Oct 30 '11 at 13:44
  • 2
    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++. – Kerrek SB Oct 30 '11 at 14:22