繁体   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

基本上,用户会输入

'q',它将退出功能。

或输入“ r”,“ 1”,“ 3”,它应该执行某些操作。

我之前使用过sscanf,但这只是因为我知道int会在选择字符之后出现。

对于最后一个

f用户必须输入'f'然后输入文件名,它应该打开文件。

我如何使用sscanf将这部分拟合到方程中。 目前,我的代码如下所示。

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

但是,如果用户输入“ f”“ filenamehere.exe”,则此操作将无效

您要做的是将阅读分为两个步骤:首先获得用户想要的模式,然后根据该模式采取行动...

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