嗨,我有这段代码用于将文本文件读入字符串
void addStu (BST_TREE* list)
{
// Local Declarations
COMPANY* stuPtr;
FILE* fp;
int i = 0;
char fileName[25];
char buffer [100];
char* tempString;
// Statements
stuPtr = (COMPANY*)malloc (sizeof (COMPANY));
stuPtr->name = (char*) malloc(128 * sizeof(char));
stuPtr->market = (char*) malloc(128 * sizeof(char));
stuPtr->initial = (char*) malloc(128 * sizeof(char));
tempString = (char*) malloc(128 * sizeof(char));
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
{
printf("Error cannot open the file!\n");
exit(101);
}
while(fgets(buffer, 100, fp) != NULL)
{
if (!stuPtr)
printf("MEmory overflow!\n"), exit(101);
tempString = buffer;
stuPtr->name = strtok(tempString, ";");
sscanf(buffer, "%15s %15s %f ", stuPtr->market, stuPtr->initial, &(stuPtr->stock));
BST_Insert(list, stuPtr);
i++;
} // end while
} //addStu
此代码无法正常工作,因为当我什至没有修改它时缓冲区会不断变化
这是我的输入
Microsoft Corporation; NASDAQ MSFT 259.94B
Yahoo! Inc.; NASDAQ YHOO 37.67B
Baidu.com, Inc. (ADR); NASDAQ BIDU 8.64B
CNET Networks, Inc.; NASDAQ CNET 1.13B
QuickLogic Corporation; NASDAQ QUIK 88.62M
Answers Corporation; NASDAQ ANSW 53.49M
Apple Inc.; NASDAQ AAPL 114.17B
例如,当我尝试读取第一行时,我能够Microsoft Coporation
使用字符串令牌获取 stuPtr->name 以包含,在此之后 tempString 也将被修改为包含Microsoft Coporation
,由于某种原因,不应该更改的缓冲区, 也更改为stuPtr->market
, stuPtr->initial
, 并且stuPtr->stock
输入值错误。
为什么缓冲区没有被修改就改变了?如何修复此代码以使其正常工作?
提前感谢您的帮助