当我在下面执行我的代码时。它等待输入文件名称的输入。但它不会等待我输入文件名,而只是跳到它的_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'。 –