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