为什么我的 else 块中的第一个 ofstream 输出缺少填充字符?
Why is my first ofstream output in my else block missing the fill character?
我正在使用此代码将霍夫曼树的节点输出到具有特定格式的文本文件。 if 块 运行 中的所有节点输出均符合预期,但 else 块中的第一个输出在 "L:" 之后缺少“0”填充字符。它应该输出 "L:076" 而不是输出 "L: 76"。 cout 看起来是正确的,但文本文件不是。所有未来的循环都像它们应该的那样通过 else 块输出,它只是缺少填充字符的第一个循环。这是我的输出图片
void preOrder(node* tree, std::ofstream& of) {
if (tree->label > 0) {
of << "I:" << tree->label << " ";
}
else {
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << int(tree->ch) << std::endl;
of << "L:";
of << of.fill('0');
of << std::right;
of << int(tree->ch);
of << " ";
return;
}
preOrder(tree->left, of);
preOrder(tree->right, of);
}
因为你有事瞒着我们。
#include <iostream>
int main()
{
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << 3 << std::endl;
return 0;
}
输出 003
(live example)。
请提供一个MCVE,我会编辑我的答案来帮助你。
来自 cppreference.com:
The second form (2) sets fillch as the new fill character and returns the fill character used before the call.
"The second form" 是非常量版本,适用于此处。所以我的猜测(我自己从未使用过 fill 并且我无法按原样编译你的代码)是调用被正确应用然后你将旧的填充字符(空白 space 大概)放到流中,因为你做:
of << of.fill('0');
此外,我注意到您没有设置 of
的宽度。
我正在使用此代码将霍夫曼树的节点输出到具有特定格式的文本文件。 if 块 运行 中的所有节点输出均符合预期,但 else 块中的第一个输出在 "L:" 之后缺少“0”填充字符。它应该输出 "L:076" 而不是输出 "L: 76"。 cout 看起来是正确的,但文本文件不是。所有未来的循环都像它们应该的那样通过 else 块输出,它只是缺少填充字符的第一个循环。这是我的输出图片
void preOrder(node* tree, std::ofstream& of) {
if (tree->label > 0) {
of << "I:" << tree->label << " ";
}
else {
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << int(tree->ch) << std::endl;
of << "L:";
of << of.fill('0');
of << std::right;
of << int(tree->ch);
of << " ";
return;
}
preOrder(tree->left, of);
preOrder(tree->right, of);
}
因为你有事瞒着我们。
#include <iostream>
int main()
{
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << 3 << std::endl;
return 0;
}
输出 003
(live example)。
请提供一个MCVE,我会编辑我的答案来帮助你。
来自 cppreference.com:
The second form (2) sets fillch as the new fill character and returns the fill character used before the call.
"The second form" 是非常量版本,适用于此处。所以我的猜测(我自己从未使用过 fill 并且我无法按原样编译你的代码)是调用被正确应用然后你将旧的填充字符(空白 space 大概)放到流中,因为你做:
of << of.fill('0');
此外,我注意到您没有设置 of
的宽度。