![](/img/trans.png)
[英]C - Is there a way to read a single character of user input, and not have the rest "pushed down" to the next request for input?
[英]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.