简体   繁体   中英

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. The problem is my fgets usage.

//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.

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.

The for loop is wrong.

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. 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.

There are a lot of problems in your code.

1)

char input[10];
printf("Enter a 10 character input for balance: ");

Should be:

    char input[11];

You need the '\\0' too.

2)

    fgets(input, 10, stdin);

Always check return:

    if (fgets(input, 10, stdin) != NULL){}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM