输入
void sum(int a, int b) {
a + b;
}
void quit() {
exit(0);
}
int main() {
char str[10];
int x, y;
printf("Call a function");
scanf("%s %d %d", str, &x, &y); //<-this is the part I cannot resolve
//tried to call a function but failed
if (strcmp(str, "quit") == 0)
quit();
else if (strcmp(str, "sum") == 0)
sum(x, y);
}
概括:
sum(int a, int b) 和 quit() 函数需要不同的 scanf。如果我想调用一个函数而不考虑参数,我应该如何修复它?我希望程序根据用户输入来识别要调用的函数。
加:该代码仅适用于 sum() 函数,因为 scanf() 仅接受 ["%s %d %d", str, &x, &y] 输入。但是,我希望程序同时扫描 sum() 和 quit() 。
在处理基于行的用户输入时,总是一次读取一行是有意义的。这不是函数的scanf
作用。例如,如果您使用"%s %d %d"
格式字符串,scanf
则将继续读取输入,直到它能够匹配两个数字,或者直到遇到无法匹配的字符(例如字母字符)。如果用户输入时没有在同一行输入两个数字,它将继续读取行尾的输入"quit"
,这可能不是您想要的。
为了准确读取一行输入,我建议您使用函数fgets
. 然后,如果需要,您可以sscanf
在该单行输入上使用。这样,您的程序就不会出现试图读取多行输入的问题。如果用户之后没有输入任何数字,该函数sscanf
将简单地报告它只能匹配第一个说明符。
使用函数scanf
和sscanf
,您可以检查函数的返回值以确定匹配格式字符串中的说明符的数量。
scanf
使用或sscanf
不首先检查该函数的返回值来确定匹配的参数数量是不安全的。否则,您可能正在使用不存在的结果。有关详细信息,请参阅本指南:
此外,当在or (但不是)中使用%s
格式说明符时,通常最好限制写入的字符数。否则,如果用户输入超过 9 个字符(包括终止空字符在内的 10 个字符),将发生缓冲区溢出,因为数组只有 10 个字符的空间。应始终防止缓冲区溢出,因为它会导致很难找到的错误。scanf
sscanf
printf
str
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sum( const int a, const int b )
{
printf( "The sum of %d and %d is %d.\n", a, b, a + b );
}
void quit()
{
printf( "Quitting.\n" );
exit( EXIT_SUCCESS );
}
int main( void )
{
char line[100];
char str[10];
int x, y;
int num_matched;
printf( "Call a function: " );
if ( fgets( line, sizeof line, stdin ) == NULL )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
num_matched = sscanf( line, "%9s %d %d", str, &x, &y );
if ( num_matched >= 1 && strcmp( str, "quit" ) == 0 )
quit();
else if ( num_matched >= 3 && strcmp( str, "sum" ) == 0 )
sum( x, y );
else
printf( "Bad input!\n" );
}
该程序具有以下行为:
Call a function: sum 5
Bad input!
Call a function: sum 5 7
The sum of 5 and 7 is 12.
Call a function: quit
Quitting.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句