1

I'm a new C programmer. I have got the situation when I have two files. First file has 4 columns and the second file has 2 columns. I need to compare 3rd column of the first file with the first column of the second file. I am looking for efficient C code. Do I have to convert the file into an array? How can I do that?

This is my part of code where I tried to convert a 3rd column into an array but it does not work because of incompatible types:

int countlines = 0;
char names[countlines][100];
double column1;
char column2[15];
char column3[15];
int column4;

while(!feof(pack)) {
    fscanf(pack, "%lf %s %s %i\n", &column1, column2, column3, &column4);
    names[countlines] = column3;
    countlines++;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2758935
  • 131
  • 1
  • 1
  • 8
  • 1
    http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – William Pursell Sep 11 '13 at 15:42
  • 1
    @WilliamPursell - I doubt if he is asking about the feof issue - his program has to compile first to hit the feof issue. – user93353 Sep 11 '13 at 15:45
  • user93353 You are correct, the `feof` issue is not the root of the problem. Are you suggesting that we should let a confessed newbie to the language perpetuate an error simply because that particular mistake was not asked about? That seems foolish. – William Pursell Sep 11 '13 at 16:15

1 Answers1

1

Change this

 char names[countlines][100];  

Like this , assuming you have maximum of 50 lines in your file.

#define MAX_LINES 50

char names[MAX_LINES][100];    

Make sure that after fscanf(pack, "%lf %s %s %i\n", &column1, column2, column3, &column4); this statement

conform respected variables values by printing them. and if those or fine then use strcpy() to copy strings.

strcpy(names[countlines], column3);
countlines++;  
    or 
strcpy(names[countlines++], column3);   
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • Thank you so much! For column 3 now it works. But when I try to strcpy int column4 to int ARRAY[MAX_LINES][10] it gives me: passing argument from incompatible pointer type. – user2758935 Sep 11 '13 at 16:30
  • @user2758935 if you want to store integers you just need array of integers.declaration : **int array[MAX_LINES];** and usage **array[countlines++]=column4;** and array[MAX_LINES][10] is two dimentional array, this is not required in your case. where as names[MAX_LINES][100]; is required because you need to store the array of strings , where each string is array of characters. – Gangadhar Sep 11 '13 at 16:43