我是C的初学者,从本质上讲,我试图逐个读取char文件,并将字符回显到输出,但是,在每一行的开头都包含行号。我设法弄清楚如何计算行数,但是当我尝试插入行号时,我无法弄清楚如何将其插入下一行,而不是遇到换行符后立即插入。
这是我的代码:
int main() {
int c, nl;
nl = 1;
FILE *file;
file = fopen("testWords.in", "r");
if (file) {
printf("%d. ", nl);
while((c = getc(file)) != EOF) {
if (c == '\n') {
++nl;
printf("%d", nl);
}
printf("%c", c);
}
fclose(file);
}
}
这是输出:
1. The Three Laws of Robotics:2
First: A robot may not injure a human being or, through inaction,3
allow a human being to come to harm;4
Second: A robot must obey the orders given it by human beings5
except where such orders would conflict with the First Law;6
Third: A robot must protect its own existence as long as7
such protection does not conflict with the First or Second Law;8
The Zeroth Law: A robot may not harm humanity, or, by inaction,9
allow humanity to come to harm.10
-- Isaac Asimov, I, Robot11
我相信您要在打印行号之前先打印换行符\n
。您只需将打印字符行移至if语句上方即可解决此问题。
int main() {
int c, nl;
nl = 1;
FILE *file;
file = fopen("testWords.in", "r");
if (file) {
printf("%d. ", nl);
while((c = getc(file)) != EOF) {
printf("%c", c);
if (c == '\n') {
++nl;
printf("%d", nl);
}
}
fclose(file);
}
}
无需过多更改,您可以通过记录以前的字符来防止打印多余的行号。等待打印行号,直到最后一个字符为\n
并且您在新行上。这样,EOF
将在打印无关的行号之前触发。
#include <stdio.h>
int main() {
int c, nl, p;
nl = 1;
FILE *file;
file = fopen("testWords.in", "r");
if (file) {
printf("%d. ", nl);
while((c = getc(file)) != EOF) {
if (p == '\n') {
++nl;
printf("%d", nl);
}
p = c;
printf("%c", c);
}
fclose(file);
}
}
如何将其插入下一行,而不是遇到换行符后立即插入。
简单跟踪何时读取的字符是该行的第一个字符。
这很好地处理了没有行的文件以及最后一行不以'\n'
结尾的文件。
int nl = 0;
int start_of_line = 1;
while((c = getc(file)) != EOF) {
if (start_of_line) {
printf("%d ", nl++);
}
printf("%c", c);
start_of_line = (c == '\n');
}