清空动态数组以在fgets()while循环期间重用

时间:2015-09-17 01:13:21

标签: c stack

我有一个动态数组,每次" push"调用函数,然后在main中执行剩余的操作。

要获得用户的输入,我使用带有stdin的fgets()作为我的第三个参数。 fgets()将继续运行,直到用户输入字符“q'”。因此,用户可以继续输入新的字符行,然后输入"输入"键。

我的问题是如何每次为新的输入线重置动态数组?换句话说,在"输入"之后重置动态数组。键被按下,并重新使用那个清空的动态数组?

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] = '\0';
}

由于我还使用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
}

1 个答案:

答案 0 :(得分:2)

为了提高效率和冗余,请执行此操作

buffer[0] = '\0';

现在你可以认为缓冲区的其余部分是垃圾:)。这里最好的是fgets()可以优雅地处理这种情况,只需在它读取之后附加'\0'即可。

相关问题