gpt4 book ai didi

c - 尝试清除缓冲区后继续出现段错误?

转载 作者:行者123 更新时间:2023-11-30 15:35:26 25 4
gpt4 key购买 nike

嗨,我正在编写一个简单的代码来帮助我自己理解函数指针,但后来我在尝试清除缓冲区时遇到了另一个问题,因为“\n”字符被保留,我尝试尝试清除缓冲区但是当我运行代码时遇到了另一个问题,当 else 语句为真时,我收到段错误,这是为什么?有人可以指导我清除缓冲区或更好的处理方法吗?谢谢。

               /*
* funcptrs.c
*
* Program to demonstrate the use of function pointers
*
* by Mvitagames
*/
#include <stdio.h>
#include <stdlib.h>

static void goodbye() {

printf("\nPress ENTER to exit: ");
fflush(stdin);
getchar();

}

static int add(int a, int b) { return a + b;}

static int subtract (int a, int b) { return a - b;}

int main() {
int i, j;
int result;
int (*func_ptr)(int , int );
int ch;
char buf[BUFSIZ];

atexit(goodbye);

printf("Please enter the first number: ");
scanf("%d", &i);
printf("Please enter the second number: ");
scanf("%d", &j);


while ((ch = getchar()) != '\n' && ch != EOF);

printf("Would you like to add or subtract (a/s)? ");
if (getchar() == 'a')
func_ptr = add;
else
//printf("I got here");
func_ptr = subtract;

result = func_ptr(i,j);

printf("The result is %d\n", result);


return (0);
}

最佳答案

一种解决方案是使用 fgets 读取输入行,然后使用 sscanf 进行任何转换。这避免了 scanf 在输入缓冲区中留下杂散字符的问题。结果代码如下所示

#include <stdio.h>
#include <stdlib.h>

#define MAXL 1024
static char line[MAXL];

static void goodbye() {

printf("\nPress ENTER to exit: ");
fgets( line, MAXL, stdin );
}

static int GetIntFromUser( char *prompt )
{
int result;

printf( "%s", prompt );
fflush(stdout);

if ( fgets( line, MAXL, stdin ) == NULL )
exit( 1 );
if ( sscanf(line, "%d", &result) != 1 )
exit( 1 );

return( result );
}

static char GetCharFromUser( char *prompt )
{
char result;

printf( "%s", prompt );
fflush(stdout);

if ( fgets( line, MAXL, stdin ) == NULL )
exit( 1 );
if ( sscanf(line, " %c", &result) != 1 )
exit( 1 );

return( result );
}

static int add(int a, int b) { return a + b;}

static int subtract (int a, int b) { return a - b;}

int main() {
int i, j;
int result;
int (*func_ptr)(int , int );
char ch;

atexit(goodbye);

i = GetIntFromUser( "Please enter the first number: " );
j = GetIntFromUser( "Please enter the second number: " );
ch = GetCharFromUser( "Would you like to add or subtract (a/s)? " );

if ( ch == 'a' )
func_ptr = add;
else
func_ptr = subtract;

result = func_ptr(i,j);

printf("The result is %d\n", result);

return (0);
}

关于c - 尝试清除缓冲区后继续出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com