我的 C 程序中有以下循环:
while (t != 0) {
scanf("%s", &u);
intopost(u, v);
printf("%s\n", v);
t--;
}
如果我使用gets()
函数而不是 scanf()
在循环内部,循环的运行速度比 t
的实际值小一。 。谁能解释为什么会发生这种情况?
以下是我的完整代码:
#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;
}
最佳答案
第一个 scanf
读取数字,但将换行符留在输入缓冲区中。
循环内的 scanf
会跳过 scanf
数字后留下的换行符,但 gets
不会。
因此,输入:
3
a
b
c
使用 gets
你会得到以下 3 行:
-- the newline after the 3
a
b
关于c - gets() 在 C 循环中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25307031/