我試圖在不使用fgets()
yes 的情況下在行的開頭列印行號,當我輸入多個檔案時它可以很好地列印行號,但我想得到這樣的結果。你們能幫我解決這個問題嗎?
現在結果
1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*5 ####@localhost ~ $*
期待結果
1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*####@localhost ~$*
這是我的代碼:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp;
int c, n;
n = 1;
for (int i = 1; i < argc; i ) {
if (argc < 2)
fp = stdin;
else
fp = fopen(argv[i], "r");
c = getc(fp);
printf("%d ", n);
while (c != EOF) {
putc(c, stdout);
if (c == '\n')
n , printf("%d ", n);
c = getc(fp);
}
fclose(fp);
}
return 0;
}
uj5u.com熱心網友回復:
printf("%d ", n);不知道是否有下一行時不要寫。或者,否則,printf("%d ", n);當您知道有下一個字符時,僅在檔案的開頭和換行符之后執行。
#include <stdbool.h> // for bool, true, false
bool previous_character_was_a_newline = true;
while ((c = getc(fp)) != EOF) {
if (previous_character_was_a_newline) {
previous_character_was_a_newline = false;
printf("%d ", n);
}
putc(c, stdout);
if (c == '\n') {
n ;
previous_character_was_a_newline = true;
}
}
不要寫像 那樣的代碼n , printf("%d ", n);,會讓人困惑。強烈傾向于:
if (c == '\n') {
n ;
printf("%d ", n);
}
uj5u.com熱心網友回復:
您的實作在第一行之前和每個換行符之后輸出行號,包括檔案末尾的行號。這會導致在檔案末尾出現一個額外的行號。
讓我們更精確地定義輸出:
- 你想要每行開頭的行號,如果沒有行就沒有輸出,最后一行之后沒有行號。
- 您是否希望在
1讀取新檔案時重置行計數器?我假設沒有,但cat -n確實如此。 - 你想在一個不以換行符結尾的非空檔案的末尾輸出一個額外的換行符嗎?我假設是但
cat -n不是。
這里是一個修改版本,其中的答案是沒有第一個問題,是第二個:
#include <stdio.h>
int output_file(FILE *fp, int line) {
int c, last = '\n';
while ((c = getc(fp)) != EOF) {
if (last == '\n') {
printf("%d\t", line );
}
putchar(c);
last = c;
}
/* output newline at end of file if non empty and no trailing newline */
if (last != '\n') {
putchar('\n');
}
return line;
}
int main(int argc, char *argv[]) {
int n = 1;
if (argc < 2) {
n = output_file(stdin, n);
} else {
for (int i = 1; i < argc; i ) {
FILE *fp = fopen(argv[i], "r");
if (fp == NULL) {
perror(argv[i]);
} else {
n = output_file(fp, n);
fclose(fp);
}
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373371.html
上一篇:對包含結構的表使用realloc
下一篇:交換鏈表中的陣列
