2013-09-23 22 views
-3

我是C新手,我很惊讶没有直接的功能来实现我想要的功能。fPrintf整数

我正在执行一个程序,需要将一个整数值写入一个文件。我有帮助我写入文件的代码片段:

FILE *in_file = fopen("test.txt", "w"); 
    fprintf(in_file,"Test"); 
    // all done! 
    fclose(in_file); 

此代码已成功地将字符串写入文件。现在,当我尝试写一个整数值到该文件时,它不喜欢它,因为我想fprintf中喜欢只字符串写入文件:

所以下面的代码不起作用:

int argc = 10; 
FILE *in_file = fopen("test.txt", "w"); 
    fprintf(in_file,"entry value: %d",argc); 
    // all done! 
    fclose(in_file); 

它抛出以下错误:

error: too few arguments to function ‘int printf(const char*, ...)’
printf();

现在,我试图找到如何打印整数在C文件,但没有发现任何straightfoward答案。所以我剩下两个选项,要么尝试找到一种方法将此整数转换为字符串,或者让Fprintf将整数值写入文件。

我不确定哪一个是最佳选择。有什么建议么?

+0

...傻错字...... – phonetagger

+0

你是否认为在编辑的代码'fprintf中( in_file,“entry value:%d”,argc);'仍然给你错误信息? – jxh

+0

这就是发生了什么。我能够成功打印字符串.'int something = 5; \t FILE * in_file = fopen(“test.txt”,“w”); \t fprintf(in_file,“%d”,something); //全部完成! \t fclose(in_file);'这不起作用 – TeaLeave

回答

2

在这一行fprintf(in_file,"entry value: %d,argc");您应将其更改为fprintf(in_file,"entry value: %d" , argc);

+0

其实我很抱歉。这是你已经建议的方式(in_file,“输入值:%d”,argc)。我为这种混乱感到很抱歉。 – TeaLeave

1

一个小错误,argc应该放在所有*printf方法的字符串字面之外。

fprintf(in_file,"entry value: %d",argc); 

int fprintf (FILE * stream, const char * format, ...);

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

+0

其实我很抱歉。这是你已经建议的方式(in_file,“输入值:%d”,argc)。我为这种混乱感到很抱歉。 – TeaLeave

1

尝试

fprintf(in_file,"entry value: %d", argc); 
+0

其实我很抱歉。这是你已经建议的方式(in_file,“输入值:%d”,argc)。我为这种混乱感到很抱歉。 – TeaLeave