使用cin.get()从cin获取输入

Getting input from cin using cin.get()?

本文关键字:cin 获取 输入 get 使用      更新时间:2023-10-16

我有两个问题要问你。我对c++还很陌生,我试图对这个程序进行变异,以便它可以接受变量并将它们存储在映射中。我的问题是,我实际上不知道程序从哪里得到用户的输入!

我理解它是如何通过cin来评估字符的,但它从哪里得到原始字符串有点令人难以置信。

我想它在这里接受输入?

   int result = 0;
   char c = cin.peek();

我的基本问题是,我试图让程序接受"x+3"作为输入。如果x以前没有使用过,作为输入的用户,然后将值存储在映射中。如果它已被使用,请从地图中检索它。我不希望你们帮我解决这个问题,但总的方向会很有帮助。

所以我想我的两个问题是:

1.程序从哪里获得用户输入?

2.如果流中有字符,获得识别的最佳方法是什么?(我看到isalpha()可以工作,这是正确的方向吗?)我应该给流复制一个字符串或其他东西来处理它吗?

#include <iostream>
#include <cctype>
using namespace std;
int term_value();
int factor_value();
/**
   Evaluates the next expression found in cin.
   @return the value of the expression.
*/
int expression_value()
{
   int result = term_value();
   bool more = true;
   while (more)
   {
      char op = cin.peek();
      if (op == '+' || op == '-')
      {
         cin.get();
         int value = term_value();
         if (op == '+') result = result + value;
         else result = result - value;
      }
      else more = false;
   }
   return result;
}
/**
   Evaluates the next term found in cin.
   @return the value of the term.
*/
int term_value()
{
   int result = factor_value();
   bool more = true;
   while (more)
   {
      char op = cin.peek();
      if (op == '*' || op == '/')
      {
         cin.get();
         int value = factor_value();
         if (op == '*') result = result * value;
         else result = result / value;
      }
      else more = false;
   }
   return result;
}
/**
   Evaluates the next factor found in cin.
   @return the value of the factor.
*/
int factor_value()
{
   int result = 0;
   char c = cin.peek();
   if (c == '(')
   {
      cin.get();
      result = expression_value();
      cin.get(); // read ")"
   }
   else // Assemble number value from digits
   {
      while (isdigit(c))
      {
         result = 10 * result + c - '0';
         cin.get();
         c = cin.peek();
      } 
   }
   return result;
}
int main()
{
   cout << "Enter an expression: ";
   cout << expression_value() << "n";
   return 0;
}

编辑1:我的想法是:

获取输入并将其复制到字符串流中,我将通过引用传递给函数。所以我可以在字符串流上使用peek等。

之后,当我需要更多的变量值用户输入时,我将从cin中获取用户输入。

我建议您使用std::getline读取用户输入,并对正在读取的行应用一些表达式解析算法。用户输入的分析太难了,不能用这种方法来完成。大多数人都会使用诸如ANTLR或boost::spirit之类的解析器生成器来执行此类任务。