gpt4 book ai didi

c - 将字符串写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:21 25 4
gpt4 key购买 nike

所以我要做的是按顺序将这些写入文件。我想过使用“for”循环,但我不确定该怎么做,因为如果我将 stri 与 i 作为变量一起使用,代码将无法正常工作。我基本上只是在寻找建议。提前致谢。

int main(void)              //Main calls the functions.  

FILE *fp_out;

char str1[] = "That means today is Monday! \n";
char str2[] = "That means today is Tuesday! \n";
char str3[] = "That means today is Wednesday! \n";
char str4[] = "That means today is Thursday! \n";
char str5[] = "That means today is Friday! \n";

fp_out = fopen("strings.txt", "w");

//int i;
//for (i=1; i>5; i++)
//{
//fputs(str[i]

最后几行被注释掉了,但它们是我尝试的 for 循环的开始。

最佳答案

因为您为每个字符串使用了不同的变量名称,所以您不能直接在循环中执行此操作(不创建这些指针的数组)。将字符串放在一个数组中可能更简单:

const char * str[5] = {
"That means today is Monday! \n",
"That means today is Tuesday! \n",
"That means today is Wednesday! \n",
"That means today is Thursday! \n",
"That means today is Friday! \n"
};

然后你就可以正常循环了:

for( i = 0; i < 5; i++ ) fputs( str[i], fp_out );

这与您原来的方法略有不同。因为你的数组被声明为 char 数组,所以你实际上可以修改它们,而我在这里使用的字符串文字是常量(即使你省略了 const 关键字) .但我认为您无论如何都不想在执行期间修改它们。

关于c - 将字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17034850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com