-3

我在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);
    }

}
4

3 回答 3

1

您显示的代码有多个问题,这里有几个:

  • 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

通过阅读任何体面的初学者书籍,所有这些都应该很容易理解。

于 2019-11-28T12:40:48.470 回答
0

while (strlen(s) != '\0')是错的。'\0'等于 0。字符串长度永远不会为 0,因此循环会一直持续下去,打印解释为字符的整数。

于 2019-11-28T12:36:54.867 回答
0

您可以使用变量“n”使用索引来遍历字符串字符,也可以递增从标准输入接收到的字符串指针以遍历其所有字符。

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

int main(void)
{
    string s = get_string("Name: ");

    /* First way using n to iterate */
    int n = 0;
    for (n = 0; n < strlen(s); ++n)
    {
        printf("%c", s[n]);
    }
    printf("\n");

    /* Second way increment the string pointer*/
    while (strlen(s) != '\0')
    {
        printf("%c", *s); //print the value of s
        s++; // go to the next character from s
    }
    printf("\n");

    return 0;
}
于 2019-11-28T12:47:28.387 回答