我正在开发一个循环程序,直到用户输入
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()
,虽然我不完全理解这种行为,但没有成功。
您不能使用
char
读取单个 std::getline()
,它仅适用于 std::(basic_)string
类型。所以,你将不得不:
char again
改成std::string again
,例如:int main()
{
...
string again;
do
{
...
}
while (getline(cin, again) &&
(again == "y" || again == "Y"));
...
}
operator>>
代替std::getline()
,例如:...
#include <limits>
...
int main()
{
...
char again;
do
{
...
if (!(cin >> again)) break;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (again == 'y' || again == 'Y');
...
}