[英]Error with fgets usage in c
I have written a balanced symbol checker with stacks. 我写了一个带有堆栈的平衡符号检查器。 Everything else works and I have fully tested all functions like pop push destroy isempty.
其他所有东西都可以正常工作,并且我已经完全测试了所有功能,例如pop push destroy isempty。 The problem is my fgets usage.
问题是我的fgets用法。
//fgets
char input[10];
printf("Enter a 10 character input for balance: ");
fgets(input, 10, stdin);
the part that is "not working" is the following code 下面的代码是“不起作用”的部分
int i = 0;
for (i < 10; i++;){
if (input[i] == '{' || input[i] == '[' || input[i] == '(' || input[i] == '<'){
push(&st2, input[i]);
}
}
I know my push function is working, because i have tested it as a standalone. 我知道我的推送功能可以正常工作,因为我已经将它作为独立版本进行了测试。 something like:
就像是:
push(&st2, '{');
works perfectly fine when i try to display my stack and correctly pushes the value. 当我尝试显示我的堆栈并正确推送值时,它工作得很好。 At this point I am thinking that either the initial char array with fgets is just not initializing correctly, or I have somehow managed to screw up the if/for loop.
在这一点上,我在想要么带有fgets的初始char数组未正确初始化,要么我已经设法以某种方式弄糟了if / for循环。
When I run the program the if statement conditional is never met even if i type a { [ ( or < into stdin. When I try to print our the input[10] char array my program just crashes aswell. 当我运行程序时,即使我在标准输入中键入{[(或<,也不会满足条件语句。如果尝试打印我们的input [10] char数组,我的程序也会崩溃。
The for loop is wrong. for循环是错误的。
Try 尝试
int i;
for (i = 0; i < 10; i++) {
...
}
instead. 代替。
The correct syntax is 正确的语法是
for (initialisation; condition; increment) {
body
}
So if you write this: 所以,如果你这样写:
int i = 0;
for (i < 10; i++; ) {
...
}
the following happens: 发生以下情况:
First the initialisation occurs. 首先进行初始化。
i < 10
is executed, but it is a simple logical expression which evaluates to true
and is ignored. 将执行
i < 10
,但这是一个简单的逻辑表达式,其结果为true
,将被忽略。 Then the condition is checked. 然后检查条件。
i++
evaluates to 0 (not to 1, because of the post -increment), which is interpreted as false
and the loop terminates. i++
计算结果为0(由于后递增,因此不为1),该值被解释为false
并且循环终止。
There are a lot of problems in your code. 您的代码中有很多问题。
1) 1)
char input[10];
printf("Enter a 10 character input for balance: ");
Should be: 应该:
char input[11];
You need the '\\0' too. 您也需要'\\ 0'。
2) 2)
fgets(input, 10, stdin);
Always check return: 始终检查退货:
if (fgets(input, 10, stdin) != NULL){}
3) 3)
for (i < 10; i++;){}
Is wrong, it should be: 是错误的,应该是:
for (;i < 10; i++){}
Do you see the difference ? 你看得到差别吗 ?
Now we can put them all together: 现在我们可以将它们放在一起:
#include<stdio.h>
#include<stdlib.h>
int main(void){
char input[11];
int i = 0;
printf("Enter a 10 character input for balance: ");
if (fgets(input, 10, stdin) != NULL){
for (;i < 10; i++){
/* do what you need here */
}
}
printf("Goodbye\n");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.