gpt4 book ai didi

c - C语言中printf不输出char数组

转载 作者:行者123 更新时间:2023-11-30 15:05:13 24 4
gpt4 key购买 nike

我的 C 程序出现问题,无法输出存储在 buffer[ ] 数组中的字符串。

我的代码是:

#include <stdio.h>
#include <ctype.h>

int main()
{
int textSize = 20;

int index, ch;
int count = 0;
int upperCount = 0;
int lowerCount = 0;
char buffer[textSize];

FILE *pToFile = fopen("input.txt", "r");

if (pToFile != NULL)
{
while (!feof(pToFile))
{
/* Read in a single line from "stdin": */
for(index = 0; (index < textSize) && ((ch = fgetc(pToFile)) != EOF)
&& (ch != '\n'); index++) {
if(islower(ch))
{
buffer[index] = toupper(ch);
count++;
upperCount++;
}
else if(isupper(ch))
{
buffer[index] = tolower(ch);
count++;
lowerCount++;
}
else
{
buffer[index] = (char)ch;
count++;
}
}
}
}
fclose(pToFile);

/* Terminate string with null characters: */
buffer[index] = '\0';

/* Print output out onto screen */
printf("%s\n", buffer);
printf("Read %d characters in total, %d converted to upper-case, %d to lower-case\n",
count, upperCount, lowerCount);
return 0;
}

第一个 printf 语句不会打印,但第二个语句会打印。请问谁能帮忙解释一下为什么会这样吗?

最佳答案

问题出在循环上,尤其是 while (!feof(pToFile)) 循环。

假设您的文本包含一行长度小于 19 个字符的行,并以换行符结尾。最后一点,以换行符结尾的行很重要。

当您读取文件时,会发生的情况是遇到换行符,中断内部 for 循环,然后回到外部循环。因为我们还没有传递到文件末尾,feof(pToFile) 将返回 false,然后您将返回到 for 循环。

这次在 for 循环中,第一次调用 fgetc 时,它会注意到您位于文件末尾并返回 EOF 然后你就跳出了循环。但是,由于 for 循环中的初始化表达式为 index = 0,因此您将退出循环,且 index 等于 0。

现在文件已结束,feof(pToFile) 将返回 true,然后退出外循环,然后使用 index 终止缓冲区中的字符串> 为零,即你这样做

buffer[0] = '\0';

现在您可以打印一个“空”字符串。

简单的解决方案?跳过外部 while 循环,您不需要它。

关于c - C语言中printf不输出char数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39963597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com