Answer to Question #17373 in C++ for Duaa

Question #17373
Write a program which converts any tab characters, ’\t’, occurring in an input file called
mytabs.txt, into a sequence of n spaces, where n is read from the keyboard. The resulting
file is written to myspaces.txt. In other words, if mytabs.txt contains
This file has too many tabs.
where each space above is actually a \t character, then the file myspaces.txt should look
like the following if n = 2
This file has too many tabs.
i did this code : but it's not working why?
#include<stdio.h>
#include<stdlib.h>
int main()
{

char d;
FILE * fin =fopen("mytabs.txt", "r");
FILE * fout =fopen("myspaces.txt", "w");
int n;

printf("Enter n: ");
scanf("%d",&n);

while(fscanf(fin,"%c",&d)!=EOF)
{
if(d =='\t')
{
for(int i=0;i<n;i++)
{
fprintf(fout," ");
}
}

else
{
fprintf(fout, "%c", d);
}

}
fclose(fin);
fclose(fout);

return 0;
}
1
Expert's answer
2012-10-26T11:12:11-0400
#include<iostream>

#include <fstream>

#include<conio.h>

using namespace std;

int main()

{

FILE * fin =fopen("mytabs.txt", "r");

ofstream myfile ("myspaces.txt");

int n;




printf("Enter n: ");

cin >> n;




if ( fin != NULL )

{

char line [ 128 ]; /* or other suitable maximum line size */

while ( fgets ( line, sizeof line, fin ) != NULL ) /* read a line */

{

if (myfile.is_open()) {

for (int i = 0; i < sizeof line; i++){

if(line[i] ==' ')

{

for(int i=0; i < n; i++)

{

myfile << " ";

}

}




else

{

myfile << line[i];

}

}

}

}

myfile.close();

} else perror ( "mytabs.txt" );




fclose(fin);

_getch();




return 0;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS