首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cin.get()从cin获取输入?

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

Stack Overflow用户
提问于 2015-12-01 04:28:32
回答 1查看 977关注 0票数 0

我有一个双重问题要问你。我是c++的新手,我正在尝试修改这个程序,以便它可以接受变量并将它们存储在映射中。我的问题是,我实际上不知道程序从哪里得到用户的输入!

我理解它是如何通过cin来计算字符的,但它从哪里获得原始字符串有点令人费解。

我假设它在这里接受它的输入?

代码语言:javascript
复制
   int result = 0;
   char c = cin.peek();

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

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

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

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

代码语言:javascript
复制
#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获取用户输入。

EN

回答 1

Stack Overflow用户

发布于 2015-12-01 07:30:07

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34007419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档