簡體   English   中英

為什么我的代碼在printf上打動人心?

[英]Why my code is printing an heart at printf?

這是我的代碼:

#include<stdio.h>
#include<stdlib.h>

main(){
    char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&.",text[64];
    int i, alfl=69;
    srand(time(0));
    for(i=0;i<64;i++)
        text[i] = *(alf+rand()%alfl);
    printf("%s",text);
}

但是在printf函數中,它在字符串的末尾打印一個心形。

正如其他人在注釋中所建議的(@mbratch和@KerrekSB),您需要在字符串末尾使用空終止符。

修改您的代碼,如下所示:

#include<stdio.h>
#include<stdlib.h>

main(){
    char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&.",text[64];
    int i, alfl=69;
    srand(time(0));
    for(i=0;i<63;i++)
        text[i] = *(alf+rand()%alfl);
    text[i] = '\0';
    printf("%s",text);
}

它應該可以工作,但是正如@Simon所建議的那樣,還有其他事情可以幫助改善您的代碼和對C的理解。

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

#define LEN 64

int main() { // If you don't add a return type, int is assumed. Please specify it as void or int.
    const char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&."; // This string cant be assigned to. Make sure that you stay "const-correct".
    char text[LEN]; // Please avoid magic numbers here too by using a constant
    int i, alfl = strlen(alf); // As @Simon says, it is better to not use magic constants.
    srand(time(0));
    for(i=0;i<LEN-1;i++)
        text[i] = *(alf+rand()%alfl);
    text[i] = '\0'; // make sure to null terminate your string.
    printf("%s",text);

    return 0; // If your return type is int, you must return from the function.
}

幾點建議:

  1. main應該return一個int

     int main(void) { return 0; } 
  2. 您應該使用strlen確定字符串的長度:

     alfl = strlen(alf); 
  3. 使用數組符號更容易:

     for(i = 0; i < 64; i++) text[i] = alf[rand() % alfl]; 
  4. 如果使用類似字符串的text ,則必須以'\\0'終止:

     text[63] = '\\0'; 

暫無
暫無

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

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