在C ++中获取用户输入 [英] Getting user input in C++

查看:306
本文介绍了在C ++中获取用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,允许学生写一个问题并将该问题(或字符串)存储在变量中,任何人都可以告诉我最好的方式来获取用户输入

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

感谢您的回答和评论

推荐答案

格式化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.

这篇关于在C ++中获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆