[英]printf() is only printing null values during my while loop
誰能解釋為什么在嘗試打印字符串值時會得到以下讀數:(null)(null)(null)?
這是我的代碼:
char
translate(char *fileName2)
{
char *str1;
int counted;
int count;
int printed;
int i;
FILE * fp;
i = 0;
count = 0;
counted = 0;
printed = 0;
fp = fopen(fileName2, "r");
do
{
if (!feof(fp)&&counted==0)
{
count+=1;
readToken(fp);
}
else
{
counted=1;
}
}
while (counted==0);
printf("there are %d words in the file %s\n",count,fileName2);
do
{
if (i<count)
{
//Problem here
printed=0;
i+=1;
str1 = readToken(fp);
printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
//free(str1);
}
else
{
printed=1;
printf("file has been printed\n");
printf("value of count here is:%d\n",count);
printf("value of i here is:%d\n",i);
}
}
while(counted==1&&printed==0);
fclose(fp);
return(0);
}
我只是真的不明白為什么當我嘗試打印它時為什么給我(空)str1的值。 可能有更好的方法來執行此操作,但是我不是最高級的,因此任何建議都將不勝感激...謝謝:)
編輯:這是readToken()的代碼
char *
readToken(FILE *fp)
{
int ch,index;
char *buffer;
int size = 80;
skipWhiteSpace(fp);
ch = fgetc(fp);
if (ch == EOF) return 0;
buffer = allocateMsg(size,"readToken");
index = 0;
while (!isspace(ch))
{
if (ch == EOF) break;
if (index > size - 2)
{
++size;
buffer = reallocateMsg(buffer,size,"readToken");
}
buffer[index] = ch;
++index;
ch = fgetc(fp);
}
/* push back the character that got us out of this loop */
ungetc(ch,fp);
buffer[index] = '\0';
return buffer;
}
您可能要添加
rewind(fp); //you need to reset the file pointer to the beginning.
在第二個while循環之前:
do
{
if (i<count)
{
//Problem here
printed=0;
i+=1;
str1 = readToken(fp);
printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
//free(str1);
}
else
{
printed=1;
printf("file has been printed\n");
printf("value of count here is:%d\n",count);
printf("value of i here is:%d\n",i);
}
}
while(counted==1&&printed==0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.