我在文件data1.txt中有2行(如下所示):
Da KOL -1.19503 5.27557163
MaB KOL -1.19503 5.27557163
我不确定如何使用fgets
提取特定的单词或数字,因此我使用fscanf
扫描集合的每个组件并将它们打印到另一个文件。代码是:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
main()
{
FILE *fpt1, *fpt2;
fpt1=fopen("data1.txt","r");
fpt2=fopen("data2.txt","w");
int i;
double ep, si;
char *sto1, *sto2;
for(i=0;i<2;i++)
{
fscanf(fpt1,"%s\n",sto1);
fscanf(fpt1,"%s\n",sto2);
fscanf(fpt1,"%lf\n",&ep);
fscanf(fpt1,"%lf\n",&si);
fprintf(fpt2,"%s %s %2.8lf %2.8lf\n",sto1,sto2,ep,si);
}
fclose(fpt1);
fclose(fpt2);
}
但我在文件data2.txt中获取此输出:
Da (null) 0.00000000 0.00000000
KOL (null) -1.19503000 5.27557163
虽然,所需的输出是在一行的每个组件之间有一个空格的输出,如:
Da KOL -1.19503 5.27557163
MaB KOL -1.19503 5.27557163
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
#include <stdio.h>
//A good habit is not to use "main()"
int main(int argc, char *argv[])
{
FILE *fpt1, *fpt2;
fpt1=fopen("data1.txt","r");
fpt2=fopen("data2.txt","w");
int i;
double ep, si;
char sto1[100], sto2[100]; //here neeed array
for(i=0;i<2;i++)
{
fscanf(fpt1,"%s",sto1); //without '\n'
fscanf(fpt1,"%s",sto2);
fscanf(fpt1,"%lf",&ep);
fscanf(fpt1,"%lf",&si);
fprintf(fpt2,"%s %s %2.8lf %2.8lf\n",sto1,sto2,ep,si);
}
fclose(fpt1);
fclose(fpt2);
return 0;
}
答案 1 :(得分:1)
你的想法是正确的,但我已经修改/纠正了你的代码。我使用sscanf
代替fscanf
。这是代码,
#include<stdio.h>
#define MAX 256
int main(){
FILE *pfile1 =NULL,*pfile2 = NULL;
char *sto1=NULL,*sto2=NULL,line[MAX];
double ep,si;
pfile1 = fopen("dS.txt","r");
pfile2 = fopen("dR.txt","w");
if(pfile1 != NULL || pfile2 != NULL){
while(fgets(line,255,pfile1)!=NULL){
sscanf(line,"%s %s %Lf %Lf",&sto1,&sto2,&ep,&si);
fprintf(pfile2,"%s %s %2.5Lf %2.8Lf\n",&sto1,&sto2,ep,si);
}
fclose(pfile1);
fclose(pfile2);
}
return 0;
}
答案 2 :(得分:0)
您使用了具有自动存储时间sto1
和sto2
的未初始化变量的值,并调用了未定义的行为。
在使用它们之前,指定指向它们的某些有效缓冲区的指针。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
FILE *fpt1, *fpt2;
fpt1=fopen("data1.txt","r");
fpt2=fopen("data2.txt","w");
int i;
double ep, si;
char *sto1, *sto2;
/* allocate enough size to store data */
sto1 = malloc(1000000);
sto2 = malloc(1000000);
for(i=0;i<2;i++)
{
fscanf(fpt1,"%s\n",sto1);
fscanf(fpt1,"%s\n",sto2);
fscanf(fpt1,"%lf\n",&ep);
fscanf(fpt1,"%lf\n",&si);
fprintf(fpt2,"%s %s %2.8lf %2.8lf\n",sto1,sto2,ep,si);
}
fclose(fpt1);
fclose(fpt2);
free(sto1);
free(sto2);
}
为fopen()
,malloc()
和fscanf()
添加错误检查会使此代码更好。
替代方法是使用静态分配的数组,而不是通过内存管理函数动态分配缓冲区。
#include<stdio.h>
int main(void)
{
FILE *fpt1, *fpt2;
fpt1=fopen("data1.txt","r");
fpt2=fopen("data2.txt","w");
int i;
double ep, si;
char sto1[1000], sto2[1000]; /* allocating too big array as automatic local variable may cause stack overflow */
for(i=0;i<2;i++)
{
fscanf(fpt1,"%s\n",sto1);
fscanf(fpt1,"%s\n",sto2);
fscanf(fpt1,"%lf\n",&ep);
fscanf(fpt1,"%lf\n",&si);
fprintf(fpt2,"%s %s %2.8lf %2.8lf\n",sto1,sto2,ep,si);
}
fclose(fpt1);
fclose(fpt2);
}
您可以使用静态数组