gets()如何在C中的循环内工作?

时间:2014-08-14 11:32:06

标签: c gets

我的C程序中有以下循环:

while (t != 0) {
    scanf("%s", &u);
    intopost(u, v);
    printf("%s\n", v);
    t--;
}

如果我在循环中使用gets()函数而不是scanf(),则循环运行的值比t的实际值小1。谁能解释为什么会这样? 以下是我的完整代码:

#include <stdio.h>
typedef struct stack {
    int data[400];
    int top;
} stack;
void init(stack* s) { s->top = -1; }
int empty(stack* s) {
    if (s->top == -1)
        return 1;
    else
        return 0;
}
int full(stack* s) {
    if (s->top == 399)
        return 1;
    else
        return 0;
}
void push(stack* s, char c) {
    s->top++;
    s->data[s->top] = c;
}
char pop(stack* s) {
    char x = s->data[s->top];
    s->top--;
    return x;
}
void intopost(char in[], char po[]) {
    stack s;
    char c, x;
    int i, j = 0;
    init(&s);
    for (i = 0; in [i] != '\0'; i++) {
        x = in[i];
        if (isalnum(x))
            po[j++] = x;
        else {
            if (x == ')') {
                if (!empty(&s))
                    po[j++] = pop(&s);
            } else if (x != '(') {
                if (!full(&s))
                    push(&s, x);
            }
        }
    }
    po[j] = '\0';
}
int main() {
    int t;
    char u[400], v[400];
    scanf("%d", &t);

    while (t != 0) {
        scanf("%s", &u);
        intopost(u, v);
        printf("%s\n", v);
        t--;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:3)

第一个scanf读取数字,但将换行符留在输入缓冲区中。 循环中的scanf会跳过scanf数字后留下的换行符,但gets没有。

所以,输入:

3
a
b
c

使用gets,您将获得以下3行:

   -- the newline after the 3
a
b