堆栈中大小变量输入错误 (C++)

input to size variable error in stack (c++)

本文关键字:错误 C++ 输入 变量 堆栈      更新时间:2023-10-16
#include <iostream>
using namespace std;
struct stack{
int size;
int top;
int *s;
};
void create(struct stack *st){
cout<<"enter size :";
cin>>(&st->size);      ///This line poses error when i run the program
st->top=-1;
st->s=new int[st->size*sizeof(int)];
}
void display(struct stack st)
{
for(int i:(st->s)){
cout<<i;
}
}

在 Create 函数中,当编译器尝试接受输入时,它会显示错误"错误:与'运算符>>不匹配'(操作数类型为'std::istream {aka std::basic_istream}' 和 'int*'("。该错误是无法理解的。任何人都可以帮助解决问题吗?

&st->size是一个int*。您无法从cin读入int*.由于您只需要读取大小,因此删除&应该可以修复它:

cin >> st->size;

您在display中的for循环也不正确。您需要执行以下操作:

for(int i = 0; i < size; ++i)
cout << st->s[i];

另外,这一行:

st->s=new int[st->size*sizeof(int)];

似乎很奇怪。如果你想在数组中有st->size元素,那么你只需要:

st->s = new int[st->size];