Help with my code, Please!
Hi all,
I have a text file like this:
abc c1 195
abc c1 231
RE c1 174
RE c1 978
HI c1 1125
HI c1 1125
ELA c1 269
and I want to sum up the values from the third column for the same name in the first column, e.g., for abc, there are two values, 195 and 231, I want to add them up and generate a final txt file like:
abc c1 xxx
Re c1 xxx
HI c1 xxx
ELA c1 xxx
I got some C code:
Code:
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *fin=fopen(argv[1],"r");
FILE *fout=fopen(argv[2],"w");
char t[15],t_d[15];
char c[16],c_d[16];
int tag,tag_d;
int a;
while (fscanf(fin, "%s %s %d", t,c,&tag)==3)
{
a++;
int b=0;
while (fscanf(fin, "%s %s %d", t_d,c_d,&tag_d)==3)
{
b++;
if(a==b)
continue;
else if(t==t_d)
tag += tag_d;
}
fprintf(fout, "%s %s %d\n", t,c,tag);
}
fclose(fin);
fclose(fout);
return 0;
}
This code has no error, even in the Gdb debugging. But it even does not go to the if(a==b), and the first loop only loop once. I have no idea.
I am new in C coding. Please help with any comment.
Thanks a lot in advance.
Thanks, it still does not work!
Quote:
Originally Posted by
rags_to_riches
Code:
int a;
while (fscanf(fin, "%s %s %d", t,c,&tag)==3)
{
a++;
What is the value of a when you first increment it? Answer: could be anything.
Are you aware that you cannot compare C-strings using ==, but that you must use strcmp?
Thanks, I changed code accordingly, but still doesn;t work!
Code:
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
FILE *fin=fopen(argv[1],"r");
FILE *fout=fopen(argv[2],"w");
char t[15],t_d[15];
char c[16],c_d[16];
int tag,tag_d;
int a=0;
while (fscanf(fin, "%s %s %d", t,c,&tag)==3)
{
a++;
int b=0;
while (fscanf(fin, "%s %s %d", t_d,c_d,&tag_d)==3)
{
b++;
if(a==b)
continue;
else if(strcmp(tr_name,tr_name_d)==0)
tag += tag_d;
}
fprintf(fout, "%s %s %d\n", t,c,tag);
}
fclose(fin);
fclose(fout);
return 0;
}
Does anyone have a working solution for this code???
Guys, can any experienced C programmer work out a real code for my problem?
Thanks a lot!!!