Getting user input in C++ [closed]

心已入冬 提交于 2020-01-09 10:33:25

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7944861/getting-user-input-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!