使用cin.get()从cin获取输入
Getting input from cin using cin.get()?
我有两个问题要问你。我对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之类的解析器生成器来执行此类任务。
相关文章:
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 从 R 控制台获取用户输入:Rcpp 和 std::cin
- 如何将字符输入限制为仅获取一个字符串"cin"
- 使用C - CIN获取几个整数数字,然后将它们放入数组中
- 使用cin获取类的枚举类型
- 通过从 CIN 获取运算符的输入创建类>>
- 在C++中,有没有一种简单的方法可以通过iostream::cin获取带有参数的命令调用
- C4700 未初始化的变量,应该使用 cin 获取其值
- 尝试从 cin 获取输入时陷入循环
- 使用cin.get()从cin获取输入
- 从scanf和cin获取变量
- c++ cin.获取一行到字符数组
- 从cin获取方向键
- 从cin获取输入并将其存储在一个字符变量中
- 仅从std::cin获取第一个值
- 使用getline而不是cin获取结构时的错误