gpt4 book ai didi

c - 使用 putchar() 打印之前的行数

转载 作者:行者123 更新时间:2023-11-30 20:21:07 26 4
gpt4 key购买 nike

请看一下我的代码并告诉我为什么我的输出看起来像这样。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
char ch, source_file[20];
FILE *source;
int i=1;
if( argc == 2 ) {
printf("The file being displayed is %s\n", argv[1]);

source = fopen(argv[1], "r");

if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(source) ) != EOF )
{
if(ch=='\n')
{
putchar(ch);
printf("%d.", i);
i++;
}
if(i==1)
{
printf("%d.", i);
i++;
putchar(ch);

}
else
putchar(ch);
}

fclose(source);

return (EXIT_SUCCESS);
}
}

这是输出

C:>p_gui_o3_ex3.exe asd.txt

The file being displayed is asd.txt
1.Teste
2.
Teste
3.
Teste
4.

5.
asd
6.
asd
7.
asd
8.
asd
9.
asd
10.
asd
11.
asd
12.
asd
13.
asd

最佳答案

好的,问题已解决。现在的输出看起来就像我想要的,我正在研究你们提供的小技巧。

这是输出

The file being displayed is asd.txt
1.Teste
2.Teste
3.Teste
4.
5.asd
6.asd
7.asd
8.asd
9.asd
10.asd
11.asd
12.asd
13.asd

这是固定代码。

#include <stdio.h>
#include <stdlib.h>

/*
*
*/
int main(int argc, char** argv) {
char source_file[20];
int ch;
FILE *source;
int i=1;
if( argc == 2 ) {
printf("The file being displayed is %s\n", argv[1]);

source = fopen(argv[1], "r");

if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(source) ) != EOF )
{
if(ch=='\n')
{
putchar(ch);
printf("%d.", i);
i++;
}
else if(i==1)
{
printf("%d.", i);
i++;
putchar(ch);
}
else
putchar(ch);
}

fclose(source);

return (EXIT_SUCCESS);
}
}

感谢大家的帮助。

关于c - 使用 putchar() 打印之前的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43724943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com