C printf()在while循环期间仅打印空值
有人能解释为什么我在打印字符串的值时得到:(null)(null)(null)的读数吗 这是我的密码:C printf()在while循环期间仅打印空值,c,printf,C,Printf,有人能解释为什么我在打印字符串的值时得到:(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(fileN
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);
}
您可能需要添加
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);
do
{
如果(我想,你还没有显示readToken
,但它可能正在返回NULL
。如果你想问这个问题,你需要显示readToken
的代码和你正在读取的文件的内容。哦,你是对的。我甚至没有想到这一点,因为它在我的程序b的其他地方返回字符串效果很好但我会检查一下。它的功能基本上与fscanf()相同。请花一些时间来学习如何使用调试器、单步执行代码行、检查变量等。它将为您节省大量时间。因此它不能替代它。即使有@Dere0405良好的修复,如果fopen()
失败。建议检查fp=fopen(fileName2,“r”);如果(fp==NULL)Handle_OpenFailure();
@chux是,这绝对是一个很好的检查,我还没有添加。谢谢你的建议。
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);