带文件输入跳过条件的算法-C语言
Algorithm with file input skipping conditions - C language
在阅读教科书中的示例和练习时,我遇到了一个看起来很简单的问题:
Copy first K characters from first K lines of file input.txt into file out1.txt and rest of characters on the lines into out2.txt. Skip following L lines and then copy first L characters of the remaining lines into out1.txt and rest of the text into out2.txt.
All while keeping formatting (number of \n characters) same in all files.
我想出了以下算法并在提供的文件上对其进行了测试。
有趣的是,该程序根本不关心条件,而是简单地将前 K 个字符复制到 out1.txt 中,然后将其余字符复制到 out2.txt 中。
我调试程序的尝试没有成功,因为 Codeblocs 似乎没有看到输入文件,只是跳过了整个算法,因为初始条件不满足。
这让我发疯,老实说我看不出我做错了什么。
在你问不之前,这不是作业。
注:i
是字符计数器,l
和k
是常量。
while (chr != EOF) {
if ((line < k) && (i < k)) {
fputc(chr, out1);
} else
if ((line < k) && (i > k)) {
fputc(chr, out2);
} else
if ((line > (l+k)) && (i < l)) {
fputc(chr, out1);
} else
if ((line > (l+k)) && (i > l)) {
fputc(chr, out2);
} else
if (chr == '\n') {
fputc(chr, out1);
fputc(chr, out2);
line = line + 1;
i = 0;
}
i = i + 1;
chr = fgetc(input);
}
您应该首先在循环中测试 '\n'
。否则,换行符作为行的一部分输出,行数无法正确更新。
int chr;
int line = 0;
int i = 0;
while ((chr = getc(input)) != EOF) {
if (chr == '\n') {
fputc(chr, out1);
fputc(chr, out2);
line = line + 1;
i = 0;
} else {
if ((line < k) && (i < k)) {
fputc(chr, out1);
} else
if ((line < k) && (i >= k)) {
fputc(chr, out2);
} else
if ((line >= (l+k)) && (i < l)) {
fputc(chr, out1);
} else
if ((line >= (l+k)) && (i >= l)) {
fputc(chr, out2);
}
i = i + 1;
}
}
在阅读教科书中的示例和练习时,我遇到了一个看起来很简单的问题:
Copy first K characters from first K lines of file input.txt into file out1.txt and rest of characters on the lines into out2.txt. Skip following L lines and then copy first L characters of the remaining lines into out1.txt and rest of the text into out2.txt. All while keeping formatting (number of \n characters) same in all files.
我想出了以下算法并在提供的文件上对其进行了测试。 有趣的是,该程序根本不关心条件,而是简单地将前 K 个字符复制到 out1.txt 中,然后将其余字符复制到 out2.txt 中。 我调试程序的尝试没有成功,因为 Codeblocs 似乎没有看到输入文件,只是跳过了整个算法,因为初始条件不满足。
这让我发疯,老实说我看不出我做错了什么。 在你问不之前,这不是作业。
注:i
是字符计数器,l
和k
是常量。
while (chr != EOF) {
if ((line < k) && (i < k)) {
fputc(chr, out1);
} else
if ((line < k) && (i > k)) {
fputc(chr, out2);
} else
if ((line > (l+k)) && (i < l)) {
fputc(chr, out1);
} else
if ((line > (l+k)) && (i > l)) {
fputc(chr, out2);
} else
if (chr == '\n') {
fputc(chr, out1);
fputc(chr, out2);
line = line + 1;
i = 0;
}
i = i + 1;
chr = fgetc(input);
}
您应该首先在循环中测试 '\n'
。否则,换行符作为行的一部分输出,行数无法正确更新。
int chr;
int line = 0;
int i = 0;
while ((chr = getc(input)) != EOF) {
if (chr == '\n') {
fputc(chr, out1);
fputc(chr, out2);
line = line + 1;
i = 0;
} else {
if ((line < k) && (i < k)) {
fputc(chr, out1);
} else
if ((line < k) && (i >= k)) {
fputc(chr, out2);
} else
if ((line >= (l+k)) && (i < l)) {
fputc(chr, out1);
} else
if ((line >= (l+k)) && (i >= l)) {
fputc(chr, out2);
}
i = i + 1;
}
}