简体   繁体   English

读入用户输入,但必须与C中的字符串/小数/字符区分开

[英]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. 'q',它将退出功能。

Or input 'r' '1' '3' and it should do something. 或输入“ r”,“ 1”,“ 3”,它应该执行某些操作。

I've used sscanf before but that's only because I knew ints would come after the character choice. 我之前使用过sscanf,但这只是因为我知道int会在选择字符之后出现。

For the last one 对于最后一个

f the user has to type in 'f' then the filename and it should open up the file. f用户必须输入'f'然后输入文件名,它应该打开文件。

How would I fit this part into the equation using sscanf. 我如何使用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" 但是,如果用户输入“ 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...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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