繁体   English   中英

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

[英]Calling function in if statement or switch not working properly

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

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

但是,如果我调用 直接它运行完美。 但是当我调用 在 if 语句或 switch 语句中,它显示了上述输出。 , and in the fucntion but still not working.我尝试了功能,但仍然无法正常工作。

#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()将从标准输入中读取一个字符并离开 \\n。 因此,当您调用 scanf 时 - 它立即停止并且您一无所获。 要跳过空格并从非空格字符开始读取,请在格式前添加空格。

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

不要混用 %[] 和 %s

始终指定要读取的最大字符数(为空终止符留一个额外的字符)

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

哦。 并检查 scanf 的返回值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM