我应该从命令行参数打开一个文件并打印其中的值。这是我的代码:
#include <stdio.h>
int main(int argc, char* argv[])
{
float num;
char const* const filename=argv[1];
FILE* file=fopen(filename,"r");
char line[256];
int j=0;
while(fgets(line,sizeof(line),file)){
for( j=0; j<2; j++ )
{
if(j == 0)
{
fscanf(file, "%f", &num);
printf("%f \t", num);
}
else if(j == 1)
{
fscanf(file, "%f", &num);
printf("%f \n", num);
}
}
}
fclose(file);
}
这是我想要得到的输出:
1 1
2 2
3 3
这是我实际得到的:
1 1
2 2
3 3
3 3
我不明白这里发生了什么。
最佳答案
我对您的代码做了两处更改。
改变
fscanf(file,"%f",&num);
进入
sscanf(line,"%f",&num);// here
您正在循环读取输入,但您正在从文件指针获取值。所以第一行将被跳过。然后在打开文件流的同时制作测试用例。
if ( file == NULL) {
perror("fopen");
return;
}
试试这段代码,我只做了上面的改动,
#include <stdio.h>
int main(int argc, char* argv[])
{
float num;
char const* const filename=argv[1];
FILE* file=fopen(filename,"r");
if ( file == NULL) {
perror("fopen");
return;
}
char line[256];
int j=0;
while(fgets(line,sizeof(line),file) != NULL){
for(j=0; j<2;j++)
{
if(j==0)
{
sscanf(line,"%f",&num);
printf("%f \t",num);
}
if(j==1)
{
sscanf(line,"%f",&num);
printf("%f \n",num);
}
}
}
fclose(file);
}
输出:
130.000000 130.000000
210.000000 210.000000
650.000000 650.000000
324.000000 324.000000
关于c - fgets() 在 C 中打印最后一行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28644243/