[英]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.