【问题标题】:Why my code is printing an heart at printf?为什么我的代码在 printf 上打印了一颗心?
【发布时间】:2013-12-22 00:10:50
【问题描述】:

这是我的代码:

#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 函数中,它会在字符串的末尾打印一颗心。

【问题讨论】:

  • 您需要将放入text 的字符串以零结尾。如果你想对它们做一些事情,比如打印它们,C 中的字符串必须以零结尾。
  • 回答任何“C 字符串”问题:Null 终止符误解。
  • 只有我还是“and heart at printf”真的没有意义吗?

标签: c string build logic


【解决方案1】:

正如其他人在 cmets(@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:我还建议写alfl = strlen(alf);(这需要#include &lt;string.h&gt;)以避免由于错误计算alf中的字符数而导致的错误,这是人类容易做的计算机不容易做...
  • @Simon,你是对的,所以我回去改了几处。这是一个快速而肮脏的初始答案。谢谢
【解决方案2】:

几个建议:

  1. main 应该是 returnint

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

【讨论】:

  • @nonsensickle 我知道你在四处游荡。我必须迅速采取行动。
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2018-07-01
  • 2023-01-05
  • 1970-01-01
相关资源
最近更新 更多