mardi 24 février 2015

How do I store Strings in an array?

I'm fairly new to C and I designed a simple experiment to help me understand basic I/O.


I'm creating a program that will read data from a basic .txt file, store it, and allow me to manipulate it.


In this case, I'm using MyAnimals.txt which contains:



4 Dogs
3 Cats
7 Ducks


Here is my code:



#include <stdio.h>
#include <stdlib.h>

main()
{
char szInputBuffer[50]; //Buffer to place data in
FILE *pfile;

int i;
char szAnimalName[20]; //Buffer to store the animal name string
char *pszAnimalNames[3]; //An array of 4 pointers to point to the animal name strings
int iAmountOfAnimal[3]; //An array to store the amount of each animal


pfile = fopen("MyAnimals.txt", "r");
printf("According to MyAnimals.txt, there are:\n");

for (i = 0; i <= 2; i++)
{
fgets(szInputBuffer, 50, pfile);
sscanf(szInputBuffer, "%d %s", &iAmountOfAnimal[i], szAnimalName);
pszAnimalNames[i] = szAnimalName;
printf("%d %s\n", iAmountOfAnimal[i], pszAnimalNames[i]);
}

printf("The number of %s and %s is %d\n", pszAnimalNames[1], pszAnimalNames[2], iAmountOfAnimal[1] + iAmountOfAnimal[2]);
printf("The number of %s and %s is %d\n", pszAnimalNames[0], pszAnimalNames[1], iAmountOfAnimal[0] + iAmountOfAnimal[1]);
}


However my output is:



According to MyAnimals.txt, there are:
4 Dogs
3 Cats
7 Ducks
The number of Ducks and Ducks is 10
The number of Ducks and Ducks is 7


Why is it that the value pszAnimalNames[0, 1, and 2] points to "Ducks" by the end of the program?


Desired output is:



According to MyAnimals.txt, there are:
4 Dogs
3 Cats
7 Ducks
The number of Cats and Ducks is 10
The number of Dogs and Cats is 7

Aucun commentaire:

Enregistrer un commentaire