[英]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.