首页 > 解决方案 > 无法将较小的数组复制到 C 中较大的预填充数组中

问题描述

我正在尝试将一个单词列表(每个单词都用换行符分隔)复制到一个大小为 16 的新数组中,其值都是井号字符“#”的十六进制版本。由于这些单词可能小于 16,因此 word 的最终值应该是单词本身,其余位置为“#”字符,不会从原始数组中替换。它的代码如下:

     fp = fopen("english_words.txt", "r");

        if (fp != NULL) {   
            while ((read = getline(&line, &len, fp)) != -1) {

                if (read < 16) {


                    unsigned char word[16] = {0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23, 0x23};
//read -1 and not read to ignore the last \n character in line
                    for (int i = 0; i < read - 1; i++) {
                        word[i] = line[i];
                        printf("%x", word[i]);

                    }



                    }
                    printf("\n");   


        }
        fclose(fp);
        if (line)
            free(line);


}

但是,当我打印最终输出时,似乎每个单词的最终数组似乎根本没有任何磅字符。有人可以帮忙吗?

编辑:

包含以下单词的文件的示例输入,每个单词由换行符分隔:

abacus
abalone
abandon

Output:
abacus##########
abalone#########
abandon#########

我将分别处理每个输出的单词,因此不需要将它们放在文件中。

标签: c

解决方案


                for (int i = 0; i < read - 1; i++) {
                    word[i] = line[i];
                    printf("%x", word[i]);

                }

仅以十六进制打印读取的字符,没有理由打印 23/'#'

所以如果你读算盘,它会打印616261637573而没有 23

警告如果您将 word 作为字符串 (%s) 打印,则它不包含用于结束它的空字符


做你期望的一个简单的方法是:

fp = fopen("english_words.txt", "r");
if (fp != NULL) {   
  char w[16];

  while (fscanf(stdin, "%15s", w) == 1)
    printf("%s%s\n", w, "###############" + strlen(w));
}
fclose(fp);

scanf最多可以读取一个单词的前 15 个字符,我检查它是否读得很好,将结果与 1 进行比较

该表单"###############" + strlen(w)是获取长度为 15 的字符串 '#' 的简单方法 - 读取单词的长度

执行 :

abacus
abacus##########
abalone
abalone#########
abandon
abandon#########

推荐阅读