Originally Posted by
pastitprogram
sorry i think im asking silly questions but i dnt think i understood the last 1.
So i should define by array as
char Name [5][20]; // Five entries with twenty chars long?
would i have to convert line to a string before i can attempt to assign it to my array?
Each row in the array is a char string because it has an end of string char '\0' at the last char position.
This is what I was suggesting:
Code:
#include <stdio.h>
int main(void) {
FILE *inf;
int i;
void printIt(char names[][20], int i);
char names[20][20] = {{ '\0' }}; //fills the array with end of string markers
if((inf = fopen("text.txt", "rt")) == NULL)
return 1;
i = 0;
while((fscanf(inf, "%s", names[i])) != EOF)
i++;
printIt(names, i);
i = getchar();
return 0;
}
void printIt(char names[][20], int NamesNum) {
int i;
for(i = 0; i < NamesNum; i++)
printf("%s\n", names[i]);
}
/* Where text.txt file had the contents:
Ann
Barbara
Charles
David
Edward
Frank
*/
Passing around 2D arrays and getting rows to print as a string, can be a little dodgy.
Now I'd add the array names2[][], and do basically the same thing. Load it from the file into your names2 array, and then call printit() to be sure it's loaded right.
Now you're *finally* ready for your two for loops, as I showed earlier, (also suggested by DaveH).
Did you say the first and last names were listed in the same file?
If so, then i and j in the two for loops, can reference the very same array, and you don't need a second array, at all.
Code:
for(i etc. ) //handles first names
{
for(j etc. ) //handles last names
{
printf( "first name: %s, last name: %s", names[i], names[j]);
}
}