为什么我的程序输出中有空格?

时间:2016-03-20 16:01:57

标签: c++

  

刻录DVD时,必须始终向表面上的激光束点燃数据,否则DVD会失效。大多数领先的DVD刻录应用程序都使用循环缓冲区将数据从硬盘流式传输到DVD上。第一部分,“写入过程”用数据填充循环缓冲区,然后当激光束将凹坑烧到DVD表面时,“刻录过程”开始从缓冲区读取。如果是缓冲区   开始变空,应用程序应该继续填满   使用磁盘中的新数据清空缓冲区中的空间。实现这一点   使用循环队列的场景。

对于上述问题,我编写了如下代码

#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;
    }
}

我不知道为什么在代码运行时我得到了一个白痴

enter image description here

有人能指出我犯错的地方吗?

1 个答案:

答案 0 :(得分:1)

您忘记致电initialize,因此q.fq.r不是-1。在您的情况下,它们是0,因此系统认为a[0]中已存在某些内容并打印出来。它不可打印,因此您只能在其后看到\t。出于这个原因,初始化应该在一个你不能忘记调用的构造函数中完成。

从C ++ 11开始,您可以直接使用

初始化fr
struct queue
{
    char a[max];
    int f=-1, r=-1;
} q;
相关问题