输入

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,&amp;x,&amp;y]输入.然而,我希望程序同时扫描sum()和quit().

推荐答案

在处理基于行的用户输入时,每次读取一行是有意义的.这不是函数scanf的功能.例如,如果使用"%s %d %d"格式字符串,则scanf将继续读取输入,直到它能够匹配两个数字,或者直到它遇到无法匹配的字符(例如字母字符).如果用户输入"quit"而没有在同一行上输入两个数字,它将继续读取超过行尾的输入,这可能不是您想要的.

对于只读取一行输入,我建议您使用函数fgets.如果你愿意,你可以在这一行输入中使用sscanf.这样,您就不会有程序试图读取多行输入的问题.如果用户之后没有输入任何数字,函数sscanf将简单地报告它只能匹配第一个说明符.

使用函数scanfsscanf,可以判断函数的返回值,以确定格式字符串中匹配了多少说明符.

使用scanfsscanf的结果而不首先判断该函数的返回值以确定匹配了多少个参数是不安全的.否则,您可能正在使用不存在的结果.有关更多信息,请参阅本指南:

A beginners' guide away from scanf()

此外,在scanfsscanf(而不是printf)中使用%s格式说明符时,通常最好限制写入的字符数.否则,如果用户输入超过9个字符(10个字符,包括终止的空字符),则会出现buffer overflow,因为数组str只有容纳10个字符的空间.应该始终防止缓冲区溢出,因为它会导致很难找到的错误.

#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.

C++相关问答推荐

Mbed TLS:OAEP的就地en—/decryption似乎不起作用'

ATTiny1606定时器TCA 0中断未触发

增加getaddrinfo返回的IP地址数量

警告:C++中数组下标的类型为‘char’[-Wchar-subpts]

如何使fputs功能提示错误输入并要求用户重新输入.程序停止而不是请求新的输入

将 struct 变量赋给自身(通过指针取消引用)是否定义了行为?

试图从CSV文件中获取双精度值,但在C++中始终为空

预先分配虚拟地址空间的区域

变量的作用域是否在C中的循环未定义行为或实现定义行为的参数中初始化?

错误...的多个定义(&Q)首先在这里定义&

Fprintf正在写入多个 struct 成员,并且数据过剩

C程序向服务器发送TCPRST

S,在 struct 中创建匿名静态缓冲区的最佳方式是什么?

如何在C中用bool进行文件I/O?

可以对两种 struct 类型中的任何一种进行操作的C函数

通过GTK';传递回调参数;s g_signal_connect()导致C中出现意外值

比 * 更快的乘法

当循环变量在溢出时未定义时,可以进行哪些优化?

在 SDL 中将鼠标位置设置为 (0,0)

从 COBOL 调用外部 C 库