【发布时间】:2015-12-01 07:30:07
【问题描述】:
我有一个双重问题要问你。我对 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: 我的想法是这样的:
获取输入并将其复制到我将通过引用函数传递的字符串流。所以我可以在 stringstream 上使用 peek 等。
之后,当我需要更多用户输入变量值时,我将从 cin 获取用户输入。
【问题讨论】: