ignore white spaces while looping and remove excess whitespaces

so the loop goes executes about 1082 times im trying to start a new line every 71st character, and remove excess white spaces from my text file. I also want to output the total line in the textfile. Can someone please explain this how you would do this.





int reformat(int length, ifstream& ist, ofstream& ost) {
int Max_length=0;

int reset=0;

if (ist) {
ifstream ist ("story1.txt");
int ch;
while((ch = ist.get()) != EOF){

{ ost<<char(ch);
cout<<char(ch);
Max_length=Max_length+1;
//------------------------------------------------------------------------------


if (Max_length=71) {

ost<<"\n"<<char(ch);
cout<<"\n"<<char(ch);

Max_length=reset;
}


//------------------------------------------------------------------------------

}
}
cout<<"looped "<<Max_length<<'\n';
}
}

int main(int argc, char* argv[])

{


int length=70;
cout <<"Please enter input txt file name to be formatted:\n ";
string iname;
cin >> iname;
ifstream ist(iname.c_str()); // ist is an input stream for the file named name
if (!ist) exit(EXIT_FAILURE);


cout <<"Please enter name of txt output file to for the new formatted version:\n";
string oname;
cin >>oname;
ofstream ost(oname.c_str()); // ost is an output stream for a file named name
if (!ost) exit(EXIT_FAILURE);


cout<<reformat(length,ist,ost);






}
Last edited on
Instead of what you have written , try this , i m sure It would work.

1
2
3
4
5
6
if (Max_length/71==0) {

ost<<"\n"<<char(ch);
cout<<"\n"<<char(ch);

}


You don't need to reset MaxLength every time it count goes to 71...

Last edited on
@shysan21: That is integer division, 1/71 = 0. It would be better to have (Max_length%71 == 0).

I think reseting the variable make more sense too, if Max_length is never reset then eventually it will overflow.

I would have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while(ist.get(ch) {  // EOF is taken care of by this operation

  if (ch != '\s' && ch != '\t'){ // Add whatever white space you don't want printed
    ost<<char(ch);
    cout<<char(ch);
    Max_length++;
  }

  if (Max_length==71) { // Make sure to have two = signs here
    ost<<"\n"<<char(ch);
    cout<<"\n"<<char(ch);
    Max_length= 0 ; // No need for a reset variable, just make it zero
  }
}
Last edited on
Topic archived. No new replies allowed.