File io leest niet alles

Status
Niet open voor verdere reacties.

manhaeve5

Gebruiker
Lid geworden
9 jan 2007
Berichten
276
Hallo. Ik ben momenteel bezig aan een run-lenght compressie methode.
De werking is als volgt:
Hij leest een getal in.
Kijkt of dit getal hetzelfde is als het vorige
Zoja?times++;
code:
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
void encrypt();
using namespace std;

int main()
{
    encrypt();
    cout<<"klaar"<<endl;
    cin.get();
    return 0;
}
void encrypt(){
ifstream input("comp.txt");
ofstream output("comp2.txt");
int currnumb=0,prevnumb=0,times=1;
bool firsttime=true;
bool gedaan;
while(!input.eof()){                    
input>>currnumb;
gedaan = false;
if(firsttime == false){
if(currnumb==prevnumb){
times++;
}
else{
if(times>=4){
output<<prevnumb<<"["<<times<<"] ";  
gedaan = true; 
}
else{
for(int a = 0; a< times;a++)
output<<prevnumb<<" ";
gedaan = true; 
     }//end check if times < 4
     
times=1;

}

}//end for check firsttime
prevnumb=currnumb;
firsttime=false;

}//end while loop
output.close();
input.close();

}
maar ik heb het probleem dat hij de laatste serie van gelijke getallen niet wegschrijft naar comp2.txt
hoe komt dit?
 
hoi,

Dit komt omdat je enkel de prevnumbers opslaat.

Code:
output<<prevnumb<<" ";

Zo zal de laatse nooit een previous kunnen worden en dus een current blijven.

Dit kan je verhelpen door op het einde de current number er in op te slaan.
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
void encrypt();
using namespace std;

int main()
{
    encrypt();
    cout<<"klaar"<<endl;
    cin.get();
    return 0;
}
void encrypt(){
ifstream input("comp.txt");
ofstream output("comp2.txt");
int currnumb=0,prevnumb=0,times=1;
bool firsttime=true;
bool gedaan;
while(!input.eof()){
                  
input>>currnumb;
gedaan = false;
if(firsttime == false){
if(currnumb==prevnumb){
times++;

}
else{
if(times>=4){
output<<prevnumb<<"["<<times<<"] ";  
gedaan = true; 
}
else{
for(int a = 0; a< times;a++)
output<<prevnumb<<" ";
gedaan = true; 
cout <<"\npn:"<<prevnumb<<"\n";
cout <<"cn:"<<currnumb<<"\n";
     }//end check if times < 4
     
times=1;

}

}//end for check firsttime
prevnumb=currnumb;
firsttime=false;

}//end while loop
[SIZE="3"]output<<currnumb;[/SIZE]
output.close();
input.close();

}

william:cool:
 
Laatst bewerkt:
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan