我正在尝试将单词列表(每个单词之间用换行符分隔)复制到大小为16的新数组中,其值均为井号字符“#”的十六进制版本。由于这些单词可能小于16,因此单词的最终值应为单词本身,其余位置为“#”字符,这些位置不会从原始数组中替换。其代码如下:
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#########
我将分别处理每个输出的单词,因此不需要将它们放在文件中。
答案 0 :(得分:1)
for (int i = 0; i < read - 1; i++) {
word[i] = line[i];
printf("%x", word[i]);
}
仅打印十六进制的读取字符,没有理由打印23 /'#'
因此,如果您阅读算盘,其中会显示 616261637573 ,但不会显示23
警告,如果将单词打印为字符串(%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#########