gpt4 book ai didi

c++ - 文件输出中的错误字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:49:49 25 4
gpt4 key购买 nike

递归地将最优二叉搜索树的前序遍历写入 .txt 文件。代码是:

 void PrintTree(int i, int j, int space)
{
if(i < j)
{
outfile.write("", space++);
outfile<<A[Rt[i][j]]<<endl;
PrintTree(i, Rt[i][j], space);
PrintTree(Rt[i][j] + 1, j, space);
}
else
{
outfile.write("",space); //This line
outfile.write("-\n",2);
}
}

此输出适用于小树,例如最多 7-10 棵。不仅如此,还给我带来了一些坏角色,而且我似乎无法找到它们的来源。

F

A

-

C

B

-

-

E

D

Ì-

Ì-

-

K

I

H

G

Ì-

Ì-

-

J

-

-

M

L

-

-

O

N

Ì-

Ì-

-

是我得到的输出示例。我不知道该代码中的“Ì”字符是什么。

const int n = 15;
char A[n] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'};
int P[n] = {150, 25, 50, 25, 50, 125, 25, 75, 75, 50, 150, 75, 50, 25, 50};

int S[n+1][n+1] = {};
int Rt[n+1][n+1] = {};

这些都是我的初始数组。(上图)

 PrintTree(0, n, 0);

是我最初调用打印树。 S[][] 是我在评论中链接的文件中的数组……它是数字。 Rt[][] 包含对应于 A[n] 的数字。所以,Rt[i][j] = 1;映射到 A[1],即“B”。

数组本身不会被越界访问,只有当“空间”变为 4 或更大时才会发生这种情况,因此这将是递归的 4 层深度。

最佳答案

这几乎可以肯定是您跟踪递归深度的方式存在问题。

outfile.write("",space);

在这里,您要告诉 write() 函数打印空字符串 ""space 个字符。在一定程度上,这似乎工作正常(例如,对于您提供的输出,Ì 总是出现在深度 5 处)。

如果你查一下,ostream& write (const char* s, streamsize n)它的第一个参数是至少 n 个字符的数组,第二个参数是要写入的字符数。相反,你应该这样做:

outfile << std::string(spaces, ' ') << '-' << std::endl;

这将创建一个长度为 spaces 的新空白字符串并将其写入 outfile 流。

关于c++ - 文件输出中的错误字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645333/

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