简体   繁体   中英

Read in user input but have to distinguish from string/decimal/character in C

q - quit the program immediately. 
r <int> - //does something
i <int1> <int2> - //does something
d <int1> <ind2> - //does something
t <int1> <int2> - //does something
l - // does something
f <filename> - // does something

Basically a user would input

'q' and it would quit the function.

Or input 'r' '1' '3' and it should do something.

I've used sscanf before but that's only because I knew ints would come after the character choice.

For the last one

f the user has to type in 'f' then the filename and it should open up the file.

How would I fit this part into the equation using sscanf. Currently my code looks like this.

printf("Please enter a choice ");
sscanf(sentence," %c %d %d", &choice, &val1, &val2)

but this wouldn't work if the user enters in 'f' "filenamehere.exe"

What you want to do is break your read up into two steps... first get the mode the user wants, then take action based on what the mode is...

char mode;

printf( "Please enter a choice " );
if( scanf( "%c", &mode ) < 1 )
{ 
    printf( "Could not read input\n" );
    exit( -1 );
}

switch( mode )
{
    case 'q': exit( 0 );
    case 'r':
    {
        int value;
        if( scanf( "%d\n", &value ) < 1 )
        {
            printf( "command 'r' requires you to input an integer value\n" );
            exit( -1 );
        }
        // do something with value
        break;
    }
    // etc...
}

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