我有一个动态数组,每次调用"push"函数时存储字符,然后在main中执行剩余的操作。
为了获得用户的输入,我使用fgets(), stdin作为第三个参数。fgets()将继续运行,直到用户输入字符'q'。因此,用户可以继续输入新的字符行,然后按"Enter"键。
我的问题是我如何重置动态数组每次输入的新行?换句话说,在按下"Enter"键后重置动态数组,并重新使用清空的动态数组?
void reset (structStack *s, char *buffer){
int i = 0;
while(isEmpty(s)== false) //Checks to see if the dynamic array is empty
pop(s); //Calls "pop" function to decrement top value
for(i = 0; i < 300; i++) //Resetting the buffer array used with fgets()
buffer[i] = ' ';
}
因为我也使用fgets()检索字符和存储到一些静态数组,难道我不需要重置我的静态数组吗?(缓冲区是我的静态数组与fgets使用)
更新:void push ( structStack *s, char buffer){ //Called every time user inputs a character
s->dArr[s->top] = buffer; //pushing the character from fgets into a dynamic array
s->top++; //Increment the top most value in the stack for adding another character into the dynamic array
}
void pop (structStack *s){
if (isEmpty(s) == false) //Just checks if the stack is empty
s->top--;
}
char top ( structStack *s ){
if (isEmpty (s) == false){
return ( s->dArr[s->top - 1] );
}
else
return 'n'; //Just a random letter
}
出于效率和冗余的目的,请这样做
buffer[0] = ' ';
现在可以认为缓冲区的其余部分是垃圾:)。这里最好的是fgets()
可以优雅地处理这种情况,只需在它读取的任何内容后面附加一个' '
。