【发布时间】:2019-01-18 23:40:27
【问题描述】:
我正在尝试解决一个 C 程序问题:
用 C 语言创建一个程序,从文本文件中读取字符串,然后以奇偶格式重新排序字符串(先取奇数字母,然后取偶数字母;例如:如果程序读取 elephant,则重新排序的字符串将是eehnlpat)。然后将字符串写入不同的文本文件。为读写提供错误检查机制。
我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *inputFile;
inputFile = fopen("inpFile.txt", "r");
if (inputFile != NULL) {
FILE *outFile = fopen("outFile.txt", "w");
if (outFile != NULL) {
printf("file created successfully\n");
int i, j = 0;
char strf1[50];
fscanf(inputFile, "%s", &strf1);
char strf2[strlen(strf1)];
for (i = 0; strf1[i] > 0; i++) {
if (i % 2 == 0) {
strf2[j] = strf1[i];
j++;
}
}
for (i = 1; strf1[i] > 0; i++) {
if (i % 2 == 1) {
strf2[j] = strf1[i];
j++;
}
}
fprintf(outFile, "%s\n", strf2);
fclose(outFile);
} else {
printf("file could not be created\n");
}
fclose(inputFile);
} else {
printf("File does not exist.");
}
return 0;
}
我觉得一切正常,但问题是如果程序读取elephant,那么我的程序给出的重新排序的字符串是eehnlpatZ0@。额外的Z0@ 是我的问题。我不想要那个额外的东西。但我无法修复它。如果有人可以帮我解决它,那就太好了。
【问题讨论】:
-
将
char strf2[strlen(strf1)];更改为char strf2[strlen(strf1)+1];。在 C 中,字符串是以 null 结尾的,您需要为该字符留出空间。 -
char strf2[strlen(strf1)]- 不会为终止的空字符留出空间(反正你从来没有写过)。使用%s向任何printf系列提交未终止的字符串会调用未定义的行为。您不符合该格式说明符的要求。