Originally Posted by
ominub
no its an assignment for a c programming class.
i dont have a text book otherwise i would have done that.
if someone could just post a simple program that will read in a word an store it in an array that would be great. but as simple as it gets... nothing but read in the characters and how to declare it an such. i can figure it out from there. thanks for the help.
No text book? Geez!
I can't test this right now because I have no access to my compiler atm, but this will be close:
Code:
//create two integer variable
int i, fetched;
/* create an array of type char, with 50 rows (names), with each row having 25 columns (or letters) for it.
Fill each row, (one curled brace), and each column in each row, (another curled brace),
with the special char that indicates an end of string marker, in C: '\0'. Note the *single*
quote marks around it - indicating it is just *one* char, not two or more char's.
*/
char names[50][25] = { { '\0' } };
FILE* in; //create a file pointer, note the all caps - a rarity in C
*/Open a file named filename, for reading as a text file and assign the pointer it returns,
to our FILE pointer, in. Note that "in" is just a name, nothing special about it.
if((in = fopen("filename", "rt")) == NULL) {
printf("File didn't open, program terminating");
return 1; //return of zero means "normal", anything else (like 1), means abnormal exit
//sometimes this convention is swapped, on different operating systems, etc.
}
//If control gets here, the file is open, so let's read in the data
/* fetched is the number of items that fscanf will be returning. When it reaches the end of the file,
it will return 0, and the for loop will end. We have to start the loop with fetched being assigned 1,
or the loop will never start at all.
Even if there are more than 50 names, stop at 50, to prevent our program from crashing.
for(i = 0, fetched = 1; i < 50 && fetched; i++) {
fetched = fscanf(in, "%s", &names[i]);
}
/* now:
names[0] will be our first name
names[1] will be out second name
names[0][0] will be the first letter in the first name
names[1][0] will be the first letter in the second name, etc.
Note: Our 50th name will be in names[49]
*/
I don't like posting code that I have not had a chance to compile or look up in a book. This is the best I can do without that help.