使用逗号而不是“\n”时省略控制台输出
Console output omitted when using commas instead of "\n"
我无法解释以下奇怪的行为:
在 inOrder()
函数中,如果我写 printf("%d\n", node->value)
(因此使用 "\n"
)一切正常,程序给出以下输出:
5
8
10
Printing Tree.
8,5,10,5
8
10
如果我写 printf("%d,", node->value)
(因此只用“,
”而不是“\n
”)程序只会给我以下输出。
5,8,10,Printing Tree.
如您所见,树的值没有打印出来,在重复的 inOrder 遍历中也没有打印出来。
你对这种行为有解释吗?这与 puts()
和 printf()
在同一行的组合使用有关吗? puts()
是否可以添加一个指示字符串结尾的字符?
(我正在使用 Xcode)
完整程序如下:
#include <stdio.h>
typedef struct Node Node;
struct Node
{
int value;
Node *left;
Node *right;
};
void printTree(Node *root)
{
puts("Printing Tree.");
printf("%d,", root->value);
printf("%d,", root->left->value);
printf("%d,", root->right->value);
}
void inOrder(Node *node)
{
if(node!=NULL)
{
inOrder(node->left);
printf("%d,", node->value);
inOrder(node->right);
}
}
int main(int argc, const char * argv[])
{
Node a = {10, NULL};
Node b = {5, NULL};
Node root = {8, &b, &a};
inOrder(&root);
printTree(&root);
inOrder(&root);
}
这里要注意的一点是,标准输出是行缓冲的。当你调用 printf()
而没有 newline
时,要发送到标准输出的数据被发送到输出缓冲区,但不会立即 flushed 到输出屏幕.
A \n
有助于刷新 缓冲区到输出屏幕立即。
或者,您可以使用 fflush(stdout)
手动刷新缓冲区。
stdout
输出在 \n
.
上缓冲
打印最后一个 \n
或使用
禁用缓冲
setvbuf(stdout, NULL, _IONBF, 0);
我无法解释以下奇怪的行为:
在 inOrder()
函数中,如果我写 printf("%d\n", node->value)
(因此使用 "\n"
)一切正常,程序给出以下输出:
5
8
10
Printing Tree.
8,5,10,5
8
10
如果我写 printf("%d,", node->value)
(因此只用“,
”而不是“\n
”)程序只会给我以下输出。
5,8,10,Printing Tree.
如您所见,树的值没有打印出来,在重复的 inOrder 遍历中也没有打印出来。
你对这种行为有解释吗?这与 puts()
和 printf()
在同一行的组合使用有关吗? puts()
是否可以添加一个指示字符串结尾的字符?
(我正在使用 Xcode)
完整程序如下:
#include <stdio.h>
typedef struct Node Node;
struct Node
{
int value;
Node *left;
Node *right;
};
void printTree(Node *root)
{
puts("Printing Tree.");
printf("%d,", root->value);
printf("%d,", root->left->value);
printf("%d,", root->right->value);
}
void inOrder(Node *node)
{
if(node!=NULL)
{
inOrder(node->left);
printf("%d,", node->value);
inOrder(node->right);
}
}
int main(int argc, const char * argv[])
{
Node a = {10, NULL};
Node b = {5, NULL};
Node root = {8, &b, &a};
inOrder(&root);
printTree(&root);
inOrder(&root);
}
这里要注意的一点是,标准输出是行缓冲的。当你调用 printf()
而没有 newline
时,要发送到标准输出的数据被发送到输出缓冲区,但不会立即 flushed 到输出屏幕.
A \n
有助于刷新 缓冲区到输出屏幕立即。
或者,您可以使用 fflush(stdout)
手动刷新缓冲区。
stdout
输出在 \n
.
打印最后一个 \n
或使用
setvbuf(stdout, NULL, _IONBF, 0);