當我在下面執行我的代碼時。它等待輸入文件名稱的輸入。但它不會等待我輸入文件名,而只是跳到它的_getch()部分。我無法添加一個句子。不工作控制檯不等待輸入。 (C語言)
代碼:
#include <stdio.h>
main() {
FILE *fp;
char fnamer[100] = ""; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s", &fnamer);
fp = fopen(fnamer, "w");
if (fp == NULL)
{
printf("\n%s\" File NOT FOUND!", fnamer);
}
char c[1000];
printf("Enter a sentence:\n");
gets(c);
fprintf(fp, "%s", c);
fclose(fp);
_getch();
}
代碼工作,並等待進入一句話:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char c[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL){
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(c);
fprintf(fptr, "%s", c);
fclose(fptr);
return 0;
}
兩者是如此的相似正確的,在年底的提示,詢問了一句。這沒有意義。
可能不相關,但刪除&符號:'scanf(「%s」,&fnamer);' - >'scanf(「%s 「,fnamer);' –
[爲什麼要使用函數那麼危險 - 它不應該被使用](http://stackoverflow.com/questions/1694036/why-is這種功能非常危險 - 它不應該被使用) – LPs
如果輸入與scanf格式字符串不匹配,則'scanf'使用起來會很複雜並且毫無用處。而是使用'fgets'。 –