簡體   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