在 C++ 中获取用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7944861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:45:40  来源:igfitidea点击:

Getting user input in C++

c++stringgetlinecin

提问by melonQheadQsheep

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

感谢您的回答和评论

回答by Kerrek SB

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

格式化 I/O;取自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.

Usinggetline()意味着您可能会读取一个空行,因此值得检查结果是否为空。检查读取操作的正确执行也很好,因为用户可能会将一个空文件通过管道传输到 stdin,例如(通常,永远不要假设任何特定情况存在并为任何事情做好准备)。另一种方法是标记提取,std::cin >> name一次只读取一个单词,并将换行符视为任何其他空格。

回答by Cool_Coder

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

使用gets(),如示例所示。它简短而简单,错误最少。