C++写一个程序:打开指定文本文件,在每一行前加行号

2024-12-25 22:45:15
推荐回答(4个)
回答1:

#include
#include
#define BUFF_SIZE 50
int main()
{
char file[256],buff[BUFF_SIZE+1];
FILE* fin = NULL;
int bL = 1;
int iLN = 0; // line number

printf("Enter file path and name:");
scanf("%s",file);

if (NULL == (fin = fopen(file,"r")))
{
printf("file open error. \n");
return -1;
}

while (NULL != fgets(buff,BUFF_SIZE,fin))
{
if (bL) printf("%3d:%s",++iLN,buff);
else printf("%s",buff);
if (buff[strlen(buff)-1] == '\n') bL = 1;
else bL = 0;
}
fclose(fin);
}

回答2:

#include
#include
using namespace std;

void main() {
ofstream file;
file.open("input.txt");
file<<"aaaaaaaa\nbbbbbbbb\ncccccccc";
file.close();

ifstream filei("input.txt");
ofstream fileo;
fileo.open("output.txt");

char c;
filei>>noskipws;
int i=1;
fileo<cout<while(filei>>c) {
if(c=='\n') {
i++;
fileo<<"\n";
cout<<"\n";
fileo<cout<} else {
fileo<cout<}
}
filei.close();
fileo.close();
}

回答3:

程序如下:

#include
#include
#define BUFF_SIZE 50
int main()
{
char file[256],buff[BUFF_SIZE+1];
FILE* fin = NULL;
int bL = 1;
int iLN = 0; // line number

printf("Enter file path and name:");
scanf("%s",file);

if (NULL == (fin = fopen(file,"r")))
{
printf("file open error. \n");
return -1;
}

while (NULL != fgets(buff,BUFF_SIZE,fin))
{
if (bL) printf("%3d:%s",++iLN,buff);
else printf("%s",buff);
if (buff[strlen(buff)-1] == '\n') bL = 1;
else bL = 0;
}
fclose(fin);
}

回答4:

答案不是C的,我也想问