gpt4 book ai didi

在 if 语句或 switch 中调用函数无法正常工作

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

当我编译并运行它时,输出是:

press n to continue
n
Enter the filename: [ �h�� ]

但是,如果我直接调用 new(); 它会完美运行。但是当我在 if 语句或 switch 语句中调用 new(); 时,它会显示上述输出。我在 new() 函数中尝试了 scanffgetsgets 但仍然无法正常工作。

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

int menu();
int new();

int main(){

menu();

return 0;
}

int menu(){
printf("press n to continue\n");
//char c = getc(stdin);
char c = getchar();

if(c=='n'){
new();
}
else if(c==27){
return 0;
}

}

int new(){

char filename[50];

printf("Enter the filename: ");
//fgets(filename, 50, stdin);
scanf("%[^\n]s", filename);
printf("[ %s ]\n\n", filename);

return 0;
}

最佳答案

getchar() 将从 stdin 读取一个字符并保留\n。所以当你调用 scanf 时 - 它会立即停止,你什么也得不到。要跳过空格并开始从非空格字符读取,请在格式前添加空格。

scanf(" %49[^\n]", filename);

不要混合%[]和%s

始终指定要读取的最大字符数(为 nul 终止符留下一个附加字符)

并以最高警告级别进行编译 - 这样您就不会在没有返回的情况下离开菜单功能。

哦。并检查scanf的返回值

if(scanf(" %49[^\n]", filename) == 1)
printf("[ %s ]", filename);

关于在 if 语句或 switch 中调用函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46412944/

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