Let's say I wanna read a strings from a file and store them into a string array.
char array [] [80];
Let's say I wanna read a strings from a file and store them into a string array.
char array [] [80];
How many strings do you think that you allocate this way ?Originally Posted by blackswan
BTW you forgot to ask a question.
Kurt
Oh, yes I forgot. I was in a hurry... Okey, I know I can have strings like this:
char *array[]={"one", "two"....};
But I want to make an array of strings which wont be initialized at first. And then when Ill do the reading of the file, I want to add each line in the array.
so I first make ,let's say 80 strings array like this char *array[80], but how can I read lines from the file into that string.
Code:fscanf(stream,``%s'', array[i]);
Would the above code work? I think I trieds this before ,but I think it didn't work...
With the declaration
you are only allocationg space for 80 pointers to strings and no space for the actual strings. You would have to do something like this:Code:char *array[80];
don't forget to free the strings after using themCode:char * array[80]; char buffer[200]; int cou = 0; while ( cou < 80 && 1 == fscanf(stream,"%s", buffer) ) { array[cou]= malloc(strlen(buffer)+1); strcpy(array[cou], buffer); cou++; }
Kurt
edit: you are talking about reading the file line by line.
so check out fgets().
Last edited by ZuK; 10-09-2005 at 07:35 AM.
Checkout the threads in 1 and 2 pages to find
why the statement is correctCode:char arr[];
Long time no C. I need to learn the language again.
Help a man when he is in trouble and he will remember you when he is in trouble again.
You learn in life when you lose.
Complex problems have simple, easy to understand wrong answers.
"A ship in the harbour is safe, but that's not what ships are built
for"
Thank's zook. That cleared my head