我希望程序通过字符串将文字hello打印到文本文件中。使用字符串打印到c中的文本文件
#include <stdio.h>
void main()
{
char word[10] = {"hello"};
FILE*fp;
fp = fopen("C:\\temp\\Dictionary.txt", "w+");
fprintf(fp, word[0]);
}
我希望程序通过字符串将文字hello打印到文本文件中。使用字符串打印到c中的文本文件
#include <stdio.h>
void main()
{
char word[10] = {"hello"};
FILE*fp;
fp = fopen("C:\\temp\\Dictionary.txt", "w+");
fprintf(fp, word[0]);
}
你打印而不是字符串第一个字符。它也可能不是一个有效的格式。正确的电话将是fprintf(fp, "%s", word)
。并且不要忘记关闭文件。
如何扫描字符串单词并将其放入字符串数组中?我目前使用scanf(“%s”,&word_entered [5]);但它不起作用。 Thnks –
什么是word_entered的类型?用问题中的代码声明,它应该是scanf(“%s”,word)。请参阅示例:http://www.cplusplus.com/reference/cstdio/scanf/请注意,虽然scanf从std中读取,而不是从文件或其他字符串读取。使用scanf扫描字符串被认为是危险的,因为有人可以输入一个更长的字符串,然后缓冲区可以采取。 – Seva
最有可能的scanf(“%s”,word_entered [5]);是你追求的。但它取决于实际的类型声明。 – Seva
试试这个..
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
fclose(f);
我需要程序使用字符串。 –
那么除了一些基本的语法错误外,还有什么问题呢? –
不知怎的,我不正确地使用fprintf,因为文本没有显示到文本文件中。 –
完全启用您的编译器警告。它应该抱怨'fprintf(fp,word [0]);' – chux