簡體   English   中英

為什么我的字符串打印兩次?

[英]Why is my string printing out twice?

我想創建一個隨機字符串的游戲,用戶必須猜測原始字符串是什么,但是當我顯示隨機字符串時,它將打印兩次。 一次隨機化一次不隨機化 這是我的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int checkWin(char guess[], char word[]);
void jumble(char array[]);
int main()
{
    srand(time(NULL));
    char word[5] = {'h', 'e', 'l', 'l', 'o'};
    char scramble[5] = {'h', 'e', 'l', 'l', 'o'};
    char guess[5];
    jumble(scramble);
    printf("The jumled word is: %s\n",scramble);
    printf("Enter a guess: ");
    for(int i = 0; i < 5; i ++)
    {
        scanf(" %c",&guess[i]);
    }
    printf("\n");
    if(checkWin(guess,word))
        printf("You win!");
    else
        printf("You lose");
}
void jumble(char array[])
{
    int a,b,c;
    for(a = 1; a<6; a++)
    {
        b = rand()%5;
        c = rand() %5;
        if(b==c)
        {
            a--;
            continue;
        }
        char temp = array[b];
        array[b] = array[c];
        array[c] = temp;
    }
}
int checkWin(char guess[], char word[])
{
    int a = 0;
    for(int i = 0; i < 5; i ++)
    {
        if(guess[i] == word[i])
            a++;
    }
    if(a==5)
        return 1;
    else
        return 0;
}

當用戶猜測字符串時,它工作正常,但是當我嘗試顯示混亂的字符串時,我得到類似以下內容:

The jumled word is: ollehhello"
Enter a guess: hello

You win!
Process returned 0 (0x0)   execution time : 9.645 s
Press any key to continue.

我不知道這是怎么回事字符串,所以任何幫助將不勝感激。

您的字符串不是NUL終止的,因此%s格式代碼會同時在這兩個字符串中運行(如果不需要對齊填充,通常會背對背布置堆棧變量,盡管這並不是標准所保證的)最終找到一個巧合的NUL字節(在另一個編譯器上,它可能會打印出更多的亂碼或崩潰)。

要解決此問題,請使用字符串文字(隱式地添加\\0 ),手動添加\\0或將它們的大小設置為比您初始化的大小大(額外的元素隱式地為零),例如:

// Not declaring sizes; the arrays size based on the literal to size 6
char word[] = "hello";
char scramble[] = "hello";

要么

// Again, autosizing to 6
char word[] = {'h', 'e', 'l', 'l', 'o', '\0'};
char scramble[] = {'h', 'e', 'l', 'l', 'o', '\0'};

要么

// Explicit sizing to 6, implicit initialization of uninitialized element to 0
char word[6] = {'h', 'e', 'l', 'l', 'o'};
char scramble[6] = {'h', 'e', 'l', 'l', 'o'};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM