为什么我的代码在printf上打印一颗心?

时间:2013-12-22 00:10:51

标签: c string build logic

这是我的代码:

#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函数中,它会在字符串的最后打印一个心脏。

2 个答案:

答案 0 :(得分:2)

正如其他人在评论中建议的那样(@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 :(得分:1)

几点建议:

  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';