我正在尝试从新的一行开始输出到控制台,例如,如果之前的行没有以 然后输出 在输出给定的字符串之前。
我想出了这个,看起来效果不错。
#include <stdio.h>
bool newLine = true;
void Output(const char* str)
{
while(*str)
{
putchar(*str++);
}
if (*(str-1) == '\n')
{
newLine = true;
}
else
{
newLine = false;
}
}
void OutputN(const char* str)
{
if (!newLine)
{
putchar('\n');
newLine = true;
}
Output(str);
}
int main()
{
for (int i = 0; i < 10; i++) { Output("."); }
OutputN("01");
Output ("23");
Output (""); // test to see if a blank string works ok
OutputN("45");
Output ("67\n");
Output (""); // test to see if a blank string works ok after \n
Output ("89");
for (int i = 0; i < 10; i++) { Output("."); }
Output ("\n");
Output(".");
}
引用此线程“C put() without newline”有评论如下 “它可以工作,但如果标准输出没有缓冲,效率可能会非常低。”指的是在循环中重复调用 putchar 。我很喜欢做缓冲和刷新。
我的问题是,在什么情况下这会变得效率低下,是否可能给我带来任何问题。
我打算将此输出一般称为“输出”来代替
fputs(str, stdout);
1 个在树莓派 5 上,破坏了 kdle,2 个(可能更有可能出现效率问题)来自通过串行流传输输出的树莓派 pico。
不要循环,而是使用
puts()
写入整个字符串。然后检查最后一个字符是否是换行符。
您还应该检查空字符串,而不执行任何操作。如果字符串为空,您的代码将访问数组外部,从而导致未定义的行为。
void Output(const char* str)
{
if (str[0] == '\0') { // empty string
return;
}
puts(str);
newLine = str[strlen(str)-1] == '\n';
}