C++ 使用cin.get()从cin获取输入?
我有两个问题要问你。我对C++非常陌生,我尝试改变这个程序,以便它可以接受变量并将它们存储在一个地图中。我的问题是,我实际上不知道程序从用户那里得到输入 我理解它是如何通过cin来计算字符的,但是它从哪里得到原始字符串有点令人难以置信 我想它是在这里输入的C++ 使用cin.get()从cin获取输入?,c++,recursion,cin,C++,Recursion,Cin,我有两个问题要问你。我对C++非常陌生,我尝试改变这个程序,以便它可以接受变量并将它们存储在一个地图中。我的问题是,我实际上不知道程序从用户那里得到输入 我理解它是如何通过cin来计算字符的,但是它从哪里得到原始字符串有点令人难以置信 我想它是在这里输入的 int result = 0; char c = cin.peek(); 我的基本问题是,我试图让程序接受“x+3”作为输入。如果以前没有使用过x,则将其作为用户输入,然后将值存储在地图中。如果它已被使用,请从地图中检索它。我不
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;
}
#包括
#包括
使用名称空间std;
int项_值();
整数因子_值();
/**
计算在cin中找到的下一个表达式。
@返回表达式的值。
*/
int表达式_值()
{
int结果=项_值();
布尔莫尔=真;
而(更多)
{
char op=cin.peek();
如果(op='+'| | op='-')
{
cin.get();
int值=术语_值();
如果(op='+')结果=结果+值;
否则结果=结果-值;
}
否则更多=错误;
}
返回结果;
}
/**
评估cin中的下一个术语。
@返回术语的值。
*/
整数项_值()
{
int结果=因子_值();
布尔莫尔=真;
而(更多)
{
char op=cin.peek();
如果(op='*'| | op=='/'))
{
cin.get();
int值=因子_值();
如果(op='*')结果=结果*值;
否则结果=结果/值;
}
否则更多=错误;
}
返回结果;
}
/**
评估cin中发现的下一个因素。
@返回因子的值。
*/
整数因子_值()
{
int结果=0;
char c=cin.peek();
如果(c=='(')
{
cin.get();
结果=表达式_值();
cin.get();//读取“)
}
else//根据数字组合数字值
{
while(isdigit(c))
{
结果=10*结果+c-'0';
cin.get();
c=cin.peek();
}
}
返回结果;
}
int main()
{
cout我建议您使用std::getline
读取用户输入,并对正在读取的行应用一些表达式解析算法。用户输入解析太难了,无法用这种方式完成。大多数人都会使用解析器生成器,如ANTLR或boost::spirit来完成此类任务