gpt4 book ai didi

c - 我在cs50沙箱中混淆了两个程序?

转载 作者:行者123 更新时间:2023-11-30 20:57:29 25 4
gpt4 key购买 nike

我在cs50沙箱中混合了两个程序,一个是查找数组中的字符数,另一个是打印这些字符。我知道该程序是垃圾,但有人可以解释一下编译器在这里做什么吗?当我运行这个时,输出开始打印字母数字文本并且永远不会停止谢谢

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{

string s = get_string("Name: ");


int n = 0;
while (strlen(s) != '\0')
{
n++;
printf("%c", n);
}

}

最佳答案

您所显示的代码存在多个问题,其中有几个:

  • strlen(s) 永远不会为零,因为您永远不会修改或删除字符串中的字符,这意味着您有一个无限循环
  • n 是整数而不是字符,因此应使用 %d 格式说明符打印
  • '\0'(语义上)是一个字符,代表字符串终止符,它不是(语义上)值0
<小时/>

为了解决第一个问题,我怀疑您想要迭代字符串中的每个字符?然后可以用例如来完成

for (int i = 0; i < strlen(s); ++i)
{
printf("Current character is '%c'\n", s[i]);
}

但是,如果您想要的只是字符串中的字符数,那么这就是 strlen 已经为您提供的:

printf("The number of characters in the string is %zu\n", strlen(s));

如果你想在不使用strlen的情况下计算字符串的长度,那么你需要修改循环以循环直到到达终止符:

for (n = 0; s[n] != '\0'; ++n)
{
// Empty
}

// Here the value of n is the number of characters in the string s

通过阅读任何一本像样的初学者书籍,所有这些都应该很容易弄清楚。

关于c - 我在cs50沙箱中混淆了两个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088986/

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