且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中获取用户输入

更新时间:2021-10-11 23:24:20

格式化I /取自

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;
  }
}

使用 getline / code>意味着您可能读取一个空行,因此有必要检查结果是否为空。也可以检查读操作的正确执行,因为用户可以将一个空文件转换为stdin,例如(一般来说,不要假设存在任何特定情况,并为任何事情做好准备)。替代方法是令牌提取, std :: cin>> name ,它只能一次读取一个字,并像任何其他空格一样处理换行符。

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.