gpt4 book ai didi

c - 为什么这不会进入while循环?

转载 作者:行者123 更新时间:2023-11-30 19:55:37 24 4
gpt4 key购买 nike

我一直在绞尽脑汁地试图找出为什么它不会打印出测试消息并进入 while 循环。有什么想法吗?

void getInput(char * string)
{
char * tempString;
int maxLength = 1026; // Accounts for NULL and \n.
tempString = malloc(maxLength * sizeof(char));

fgets(tempString, maxLength, stdin);
size_t len = strlen(tempString);


while ((int)len > maxLength)
{
printf("Test");
if (tempString[len-1] == '\n')
{
tempString[len-1] = '\0';
len = strlen(tempString);
} // if
} // while

最佳答案

fgets(tempString, maxLength, stdin);最多读取maxLength-1字节。请参阅 fgets man page了解详情。

这意味着 strlen(tempString)必须始终小于 maxLength .

您是否想使用 <作为你的循环测试?

 while ((int)len < maxLength)

关于c - 为什么这不会进入while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824976/

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