简体   繁体   English

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

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

When I compile and run this the output is:当我编译并运行它时,输出是:

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

But, if I call the new();但是,如果我调用new(); directly it run perfectly.直接它运行完美。 But when I call new();但是当我调用new(); in if statement or switch statement, it shows the above output.在 if 语句或 switch 语句中,它显示了上述输出。 I tried scanf , fgets and gets in the new() fucntion but still not working.我尝试了scanffgets获取new()功能,但仍然无法正常工作。

#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() will read one character from stdin and leave the \\n. getchar()将从标准输入中读取一个字符并离开 \\n。 So when you call scanf - it stops immediately and you got nothing.因此,当您调用 scanf 时 - 它立即停止并且您一无所获。 To skip whitespaces and start reading from non-space character add space before format.要跳过空格并从非空格字符开始读取,请在格式前添加空格。

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

Do not mix %[] and %s不要混用 %[] 和 %s

Always specify max number of chars to read (leaving one additional char for nul-terminator)始终指定要读取的最大字符数(为空终止符留一个额外的字符)

And compile with highest warning level - so you do not leave menu function without return.并以最高警告级别进行编译 - 这样您就不会在没有返回的情况下离开菜单功能。

Oh.哦。 and check the return value of scanf并检查 scanf 的返回值

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

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

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