![]() |
2 dimension array of characters
Hi , I am stuck with two dimension array of characters.
for example, I have 4 lines in a file( lines should be treated as arrays of string) called source: i am not good at C. i hope improve soon. i need help. it is very cold. I want read the first two lines and store them in a 2-dimension array of characters called destination. I know how to read (all the lines but not the first two) but when I tried to input the line in destination I get errors: I tried strcpy, memcpy... What can I do please? B :
while( !feof(fin) ) {/* while begins*/ |
What's wrong with using your count? Just count to two, don't look for the remainder unless you have some other objective.
Be very careful using eof as a loop exit at the top of the loop. Behavior can vary depending upon whether or not the last line in the file ends with a newline. Either way you decide to go can screw up performance if the other condition occurs. You'll wind up losing the last line or using it twice. I recommend making a "while (1)" loop and exiting explicitly when you detect EOF or error. Refer to your 'fgets' documentation very carefully. |
Like DaWei said, just count to two. Here's what you can do.
[php]#include <stdio.h> #include <string.h> uhOh(char * error) { fprintf(stderr, "%s\n", error); return 1; } main() { FILE * fin; int i, count = 2; char source[256]; char destination[2][256]; if((fin = fopen("source.txt", "rb")) == NULL) { return uhOh("Cannot open file"); } for(i = 0; i < count; i++) { if(fgets(source, 100, fin) == NULL) { if(ferror(fin)) return uhOh("An error has occured, check it with ferror()"); if(feof(fin)) { printf("done\n"); return 0; } } else { strcpy(destination[i],source); printf("LINE: %s\n", destination[i]); } } fclose(fin); }[/php] You don't get to printing "done" because the for loop ends, but try filling in count = 5 instead. |
ROFL, Ruben! You KNOW that I have the uhOh function and close relatives copyrighted!!!111!!eleven!
|
Quote:
@brad sue: The uhOh function with courtesy of DaWei. |
[php]
return uhOh("An error has occured, check it with ferror()");[/php] should be: [php] return uhOh("Trouble in River City."); [/php] :D |
Quote:
Thank you very much I am writing a standard C code, not php, but I think the logic is the same.. I will try it now. Thank you B |
The 'PHP' tags don't necessarily indicate PHP code, bradsue, they cause syntax highlighting to occur whereas the ordinary 'code' tags don't. InfoGeek is teasing me because I often name the string in the function prototype as he has shown :D .
|
OOHH!
I am sorry ( I know so littlle!!) B. |
| All times are GMT -5. The time now is 5:10 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC