繁体   English   中英

我在c中的cs50沙箱中混合了两个程序?

[英]I mixed up two programs in the cs50 sandbox in c?

我在 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

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

while (strlen(s) != '\\0')是错误的。 '\\0'等于 0。字符串长度从不为 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM