【问题标题】:How can I insert a char at the beginning of a line rather than at the end?如何在行首而不是行尾插入字符?
【发布时间】:2020-01-29 02:30:33
【问题描述】:

我是 C 的初学者,本质上,我试图逐个字符地读取文件,并将字符回显到输出,而且在每一行的开头,包括行号。我已经设法弄清楚如何计算行数,但是当我尝试插入行号时,我不知道如何让它插入下一行,而不是在遇到换行符时立即插入。

这是我的代码:

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

【问题讨论】:

  • 提示:在数字之前打印换行符。你这么近!这是一个操作顺序。
  • @tadman 天啊,真不敢相信它这么简单。非常感谢!知道如何防止最后的第 11 行打印吗?
  • 建议putchar(c); 而不是printf ("%c", c); (不需要转换:) 编译器会为你优化这个,但明确表明对基本工具的理解。

标签: c io ansi


【解决方案1】:

我相信您想在打印行号之前打印换行符\n。您只需将 print char 行移到 if 语句上方即可解决此问题。

int main(void) {
    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);
    }

    return 0;
}

在不更改太多内容的情况下,您可以通过记录前一个字符来防止打印额外的行号。等待打印行号,直到最后一个字符为 \n 并且您在新行上。这样EOF 将在打印无关的行号之前触发。

#include <stdio.h>

int main(void) {
    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);
    }
    return 0;
}

【讨论】:

  • 完全修复了,不敢相信我没有早点看到。关于如何防止打印最终行号的任何建议?它读取最后一个换行符,然后在底部打印一个 11,然后是一个空行,当我希望它在 10 处停止时。
【解决方案2】:

如何让它在下一行插入,而不是在遇到换行符时立即插入。

简单地跟踪读取的字符何时是行中的第一个。

这很好地处理没有行的文件和最后一行不以'\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');
    }

【讨论】:

  • 这是一个巧妙地使用条件作为start_of_line....的切换的UV。
猜你喜欢
  • 2020-04-22
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
相关资源
最近更新 更多