繁体   English   中英

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

[英]Getting input from cin using cin.get()?

我有一个双重问题要问你。 我对C ++还是很陌生,我想对这个程序进行修改,以便它可以接受变量并将其存储在映射中。 我的问题是,我实际上不知道程序从用户那里获取输入!

我知道cin是如何通过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:我的想法是这样的:

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

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

我建议您使用std::getline读取用户输入,并将一些表达式解析算法应用于正在读取的行。 用户输入的解析过于困难,无法通过这种方式完成。 大多数人都希望将解析器生成器(例如ANTLR)或boost :: spirit用于此类任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM