即使在空字符之后,垃圾值也会打印
Garbage values are printing even after null character
此代码用于在生产中打印左递归替代方案。但是当打印替代品最终被添加垃圾值时。为什么我会收到这样的错误?
如何解决此类问题?在图像中显示输出。但这是错误的输出
#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 元素。
相关文章:
- 打印字符数组地址的正确方法
- c ++控制台应用程序,如何在控制台外部打印字符
- 无法使用 swprintf 在 WCHAR* 中打印字符*
- 存储和打印字符,但输出不是预期的
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 在带有 (void*) 强制转换的字符串中打印字符的内存地址
- C++无法打印字符变量
- 无法打印字符向量C++向量
- 为什么在编辑 fastq 文件并将输出写入新的 fastq 文件时引入不可打印字符?
- C :如何询问文件名并打印字符数组
- 循环中的 Cout 不会按定义的字符逐个打印字符
- (C++) 打印字符数组字符串的单词时出现问题
- 用putchar在屏幕上打印字符
- 在C 中使用继续语句的打印字符
- 在 for 循环 c++ 中打印字符
- 使用while和if递归打印字符
- 打印字符数组 c++
- 如何使用Xcode中的Unicode打印字符╔(和其他字符)
- cout.put() 是否推荐使用 cout<< 打印字符
- C++ 中的密码 |打印字符后删除字符