Question about goto Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main ()
{

char buffer[256];
fgets(buffer, 256, stdin);

for (int i=0; i<21; ++i)
        {
            if (buffer[i]!=' ' || buffer[i]!='-' || buffer[i]!='/'  || buffer[i]!='x' || buffer[i]!='X' || buffer[i]!='0' || buffer[i]!='1' || buffer[i]!='2' || buffer[i]!='3' || buffer[i]!='4' || buffer[i]!='5' || buffer[i]!='6' || buffer[i]!='7' || buffer[i]!='8' || buffer[i]!='9')
            {
                goto LOOPOUT;
            }
        }

printf("%s\n",buffer);

LOOPOUT:
    printf("Wrong Character\n");

    return 0;
}


This is my code inside the main function.Why even when I input 9/72X-X-8-919/9/9-XX6 from the keyboard,I still get Wrong Character from the "console window"? Instead,I think I should get what I input displaied.

How should I modify my code?
Last edited on
It's because you are using || instead &&.

If you had:

1
2
if (buffer != 'A' || buffer != 'B')
  // do sometinhg 


And set buffer = 'B', what would happen?

buffer != 'A' would be true and as you have an "statement if" only with "or", the condition will satisfied and your "statement if" would execute.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main ()
{

char buffer[256];
fgets(buffer, 256, stdin);

for (int i=0; i<21; ++i)
        {
            if (buffer[i]!=' ' && buffer[i]!='-' && buffer[i]!='/'  && buffer[i]!='x' && buffer[i]!='X' && buffer[i]!='0' && buffer[i]!='1' && buffer[i]!='2' && buffer[i]!='3' && buffer[i]!='4' && buffer[i]!='5' && buffer[i]!='6' && buffer[i]!='7' && buffer[i]!='8' && buffer[i]!='9')
            {
                goto LOOPOUT;
            }
        }

printf("%s\n",buffer);

LOOPOUT:
    printf("Wrong Character\n");

    return 0;
}


If I change my code this way,I still get a "Wrong Character" from the console window.

Can you help me fix this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
        enum { NCHARS = 21 };
        char buffer[ NCHARS+1 ] = "" ;
        fgets( buffer, NCHARS+1, stdin ) ;

        const char allowed[] = " -/xX" ;
        for( int i = 0 ; i < NCHARS ; ++i )
            if( strchr( allowed, buffer[i] ) == NULL && !isdigit( buffer[i] ) ) goto LOOPOUT ;

            // http://en.cppreference.com/w/c/string/byte/strchr
            // http://en.cppreference.com/w/c/string/byte/isdigit

        puts( buffer ) ;
        return 0 ;

    LOOPOUT:
        puts( "Wrong Character" ) ;
        return 1 ;
}
Topic archived. No new replies allowed.