gpt4 book ai didi

c++ - 即使在空字符之后也会打印垃圾值

转载 作者:行者123 更新时间:2023-11-27 23:56:46 24 4
gpt4 key购买 nike

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

如何解决这样的问题? in the image the output is displayed.but that is the wrong output

#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]!='\0';i++)
{
if(r[i]!='/')
rhs[noa][j++]=r[i];
else
{
rhs[noa++][j]='\0';
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<<"no\n";
}
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 production\n";
cin>>str;
p.makeprod(str);
p.printprod();
p.checkLR();
return 0;
}

最佳答案

makeprod 中,您正在检查输入字符串中的 / 以将终止字符添加到您的 rhs 数组中,从而将您的输入字符串必须以 / 符号结尾。您有多种选择:

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

  • 当到达输入字符串的末尾时,将空终止符 (0) 添加到 rhs

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

但你真的应该添加一些溢出检查。

关于c++ - 即使在空字符之后也会打印垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42156161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com