我正在制作一个程序,可以在控制台中自定义编写选择您自己的冒险风格的故事,同时也将其写入 .txt 文件。用户将使用 scanf() 将他们的名字输入到变量中。当我使用 fopen() 并命名文件时,我想使用格式说明符和包含其名称的变量以及单词(“%s'sAwesomeAdventure.txt,nameVariable),与 printf() 中使用的方式相同。至少这是我想做的,但我做不到,有谁知道我可以做什么吗?请您的帮助,非常感谢您。
我已经尝试过了; 1)rename()函数>>结果相同,即没有结果 2)将整个字符串组合在一个变量中,然后将变量放入 fopen() 函数中,并使用模式说明符>>no go,但我可能在这里错过了一些东西。我经常错过明显的事情。
#include <stdio.h>
int main () {
char nameVariable[] =("Rick");
FILE * fp;
//as you can see here this is not correct on the following line
fp = fopen ("%ssAwesomeAdventure.txt", nameVariable, "w+");
fprintf(fp, "Be excellent to eachother!");
fclose(fp);
return(0);
}
文件应命名为:RicksAwesomeAdventure.txt
最佳答案
谢谢威廉·珀塞尔先生。您使用 sprintf() 正确引导了我,这就是我正在寻找的结果。
包括
int main(){
char nameVariable[50];
char nameQuestion[] = ("What is Your Name?\n");
char customFileName[80];
printf(nameQuestion);
scanf("%s", nameVariable);
sprintf(customFileName, "%ssAwesomeAdventure.txt", nameVariable);
FILE * fp;
fp = fopen (customFileName, "w+");
fprintf(fp, "Be excellent to eachother!");
fclose(fp);
return(0);
}
关于c - 在C中,如何使用说明符标签将变量的 "string"内容输入到文件名中以生成动态文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608184/