Reputation: 19
When burning a DVD it is essential that the laser beam burning pits onto the surface is constantly fed with data, otherwise the DVD fails. Most leading DVD burn applications make use of a circular buffer to stream data from the hard disk onto the DVD. The first part, the ‘ writing process’ fills up a circular buffer with data, then the ‘ burning process’ begins to read from the buffer as the laser beam burns pits onto the surface of the DVD. If the buffer starts to become empty, the application should continue filling up the emptied space in the buffer with new data from the disk. Implement this scenario using Circular Queue.
For the above question I wrote the code as follows
#include<iostream>
#include<string.h>
using namespace std;
#define max 5
struct queue
{
char a[max];
int f,r;
}q;
void initialize()
{
q.f=q.r=-1;
}
int enqueue(char c)
{
if(((q.f==0)&&(q.r==max-1)) || (q.r+1==q.f))
return 1;
else{
if(q.r==-1)
{
q.r=0;
q.f=0;
}
else if(q.r==max-1)
q.r=0;
else
q.r++;
q.a[q.r]=c;
}return 0;
}
char dequeue()
{
if(q.f==-1)
{
cout<<"Empty queue";
return '\0';
}
else
{
char c = q.a[q.f];
if(q.r==q.f)
q.r=q.f=-1;
else if(q.f==max-1)
q.f=0;
else
q.f++;
return c;
}
}
void display()
{
int i;
for(i=0;i<max-1;i++)
cout<<q.a[i]<<"\t";
cout<<"\nfront: "<<q.f<<"\trear: "<<q.r<<endl;
}
int main()
{
string str,str1;
cout<<"Enter a String to write data in DVD\n";
getline(cin,str,'#');
int i,f,choice;
for(i=0;str[i]!='\0';i++)
{
f=enqueue(str[i]);
if(f==1)
{
do{
cout<<"Buffer is:\n";
display();
cout<<"Enter 1 to read and 2 to exit\n";
cin>>choice;
if(choice==1)
{
str1=str1+dequeue();
cout<<"output: "<<str1<<endl;
}
f=enqueue(str[i]);
i++;
}while(choice!=2);
}
if(choice==2)
break;
f=0;
}
}
I don't know why I am getting a whitespcae when the code runs
Can anyone point out where I am making mistake?
Upvotes: 0
Views: 597
Reputation: 909
You forgot to call initialize
, so q.f
and q.r
are not -1
. In your case, they are 0
, so the system thinks that there is already something in a[0]
and prints this. It's not printable, so you only see the \t
after it. For this reason, initialization should be done in a constructor which you can't forget to call.
Starting with C++11, you can initialize the f
and r
directly with
struct queue
{
char a[max];
int f=-1, r=-1;
} q;
Upvotes: 1