1
我对C很新,我设计了一个简单的实验来帮助我理解基本的I/O。如何将字符串存储在数组中?
我正在创建一个程序,它将从一个基本的.txt文件读取数据,存储它,并允许我操纵它。
在这种情况下,我使用MyAnimals.txt其中包含:
4 Dogs
3 Cats
7 Ducks
这里是我的代码:
#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]);
}
但是我的输出是:
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
为什么pszAnimalNames [0,1,2]在程序结束时是否指向“鸭子”?
所需的输出是:
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
您应该评论为什么必须使用malloc并且必须释放分配的内存。 – Guillermo 2015-02-24 20:48:15