即使在空字符之后,垃圾值也会打印

Garbage values are printing even after null character

本文关键字:打印 字符 之后      更新时间:2023-10-16

此代码用于在生产中打印左递归替代方案。但是当打印替代品最终被添加垃圾值时。为什么我会收到这样的错误?

如何解决此类问题?在图像中显示输出。但这是错误的输出

#include<iostream>
#include<cstring>
using namespace std;
class production
{
    private:
        char lhs;
        char rhs[10][10],lr[10][10];
        int noa;
    public:
        production()
        {
            noa=0;
        }
        void makeprod(char *str)
        {
            lhs=str[0];
            char r[20];
            strcpy(r,str+3);
            int j=0;
            for(int i=0;r[i]!='';i++)
            {
                if(r[i]!='/')
                rhs[noa][j++]=r[i];
                else
                {
                    rhs[noa++][j]='';
                    j=0;
                }
            }
            noa++;
        }
        void checkLR()
        {
            int ct=0,m=0;
            for(int i=0;i<noa;i++)
            if(lhs==rhs[i][0])
            {
                strcpy(lr[m],rhs[i]);
                m++;
                ct++;
            }
            if(ct>0)
            {
                for(int k=0;k<ct;k++)
                cout<<"Left recursion at "<<lr[k]<<"n";
            }
            else
            cout<<"non";
        }
        void printprod()
        {
            cout<<"LHS = "<<lhs<<"n";
            cout<<"RHS = ";
            for(int i=0;i<noa;i++)
            cout<<rhs[i]<<" ";
        }
};
int main()
{
    production p;
    char str[20];
    cout<<"enter a productionn";
    cin>>str;
    p.makeprod(str);
    p.printprod();
    p.checkLR();
    return 0;
}

makeprod中,您正在检查输入字符串是否/将终止字符添加到rhs数组中,因此输入字符串必须以/符号结尾。您有几种选择:

  • 要么用 0 初始化数组,所以 rhs -array 总是以 null 结尾的(独立于你的问题:初始化变量总是很好的做法(

  • 添加空终止符号 (0( 以在到达输入字符串末尾时rhs

编辑:只需在构造函数中放置一个memset(rhs, 0, sizeof(rhs)*sizeof(char));(lr相同(,输出应该没问题。这将用零初始化你的数组,因此字符串以 null 结尾。

但是您确实应该添加一些溢出检查。

你在makeprod()中可能增加noa一次太多了。
这使得 for 循环printprod()在其结束后访问 rhs 1 元素。