c - 如何在行首而不是行尾插入字符?
问题描述
我是 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
解决方案
我相信您想在打印\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;
}
推荐阅读
- mongodb - Mongo DB副本集如何为特定集合数据库配置复制
- python - Pandas.DataFrame.GroupBy.agg,聚合函数中需要的独立列。如何将其放入 agg 中?
- python - opencv python将图像读取为RGB
- azure-data-factory - 从数据工厂触发 LogicApp
- javascript - D3 选择 - 反映数据变化
- python - 查找元素中的硒打印列表
- .net - 在 Worker 服务中调用 Web API 是最佳实践吗?
- chef-infra - 如何使用刀搜索查询在 Windows 节点上运行 Chef-client 的版本
- python - pyqt5中显示带有列的选中列表的最佳小部件是什么
- c# - 仅对应用程序的一部分进行 Azure AD 身份验证