我正在编写一个程序,该程序会循环直到用户输入一个字符而不是y
或Y
来停止它。我使用std::getline()
,因为我需要在另一个函数中从用户那里获得一整行文本,并且它在我程序的那个函数中运行良好。当要求用户输入一个字符来继续或停止时,它不工作。我看到了一个编译器错误:
没有与“getline”调用匹配的函数
我正在使用std::getline()
,因为std::cin
和std::getline()
一起使用会导致不必要的行为。我不知道如何解决此问题,希望得到一些帮助。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
static int ASCII_OFFSET = 48;
//48 is the ASCII value for char '0', so we take the ASCII value of char '0' and subtract 48 to get the integer 0
void postCalculator();
int main()
{
char again = 'y';
while(again == 'y'||again == 'Y')
{
postCalculator();
cout << "Type 'Y' or 'y' to continue, or type any other letter to quit:";
getline(cin, again);
}
}
/////
///// the line: getline(cin, again); is the issue
/////
void postCalculator()
{
string equation;
stack<int> stack1;
int a, b, c, holder;
cout << "Please enter the RPN expression to be calculated:" << endl;
getline(cin, equation);
for(int i = 0; i < equation.length(); i++)
{
if(equation[i] >= '0' && equation[i] <= '9')
{
holder = static_cast<int>(equation[i]) - ASCII_OFFSET;
cout << "Token = " << holder << ", ";
stack1.push(holder);
cout << "Push " << holder << endl;
}
else if(i == ' ')
{
continue;
}
else if(equation[i] == ':')
{
break;
}
if(equation[i] == '-')
{
cout << "Token = -, ";
a = stack1.top();
stack1.pop();
cout << "Pop " << a << " ";
b = stack1.top();
stack1.pop();
cout << "Pop " << b << " ";
c = b - a;
stack1.push(c);
cout << "Push " << c << endl;
}
else if(equation[i] == '*')
{
cout << "Token = *, ";
a = stack1.top();
stack1.pop();
cout << "Pop " << a << " ";
b = stack1.top();
stack1.pop();
cout << "Pop " << b << " ";
c = b * a;
stack1.push(c);
cout << "Push " << c << endl;
}
else if(equation[i] == '/')
{
cout << "Token = /, ";
a = stack1.top();
stack1.pop();
cout << "Pop " << a << " ";
b = stack1.top();
stack1.pop();
cout << "Pop " << b << " ";
c = b / a;
stack1.push(c);
cout << "Push " << c << endl;
}
else if(equation[i] == '+')
{
cout << "Token = +, ";
a = stack1.top();
stack1.pop();
cout << "Pop " << a << " ";
b = stack1.top();
stack1.pop();
cout << "Pop " << b << " ";
c = b + a;
stack1.push(c);
cout << "Push " << c << endl;
}
}
cout << "Token = Pop " << stack1.top() << endl << endl;
stack1.pop();
}
我尝试过使用std::cin
而不是std::getline()
,以及std::cin.clear()
,尽管我不完全理解其行为,但都没有成功。
1条答案
按热度按时间x9ybnkn61#
你不能用
std::getline()
读取一个char
,它只适用于std::(basic_)string
类型。因此,你必须:char again
更改为std::string again
,例如:operator>>
代替std::getline()
,例如: