我在Windows上使用CodeBlocks编写了代码。但是当我在Linux上使用GCC编译器运行代码时,我遇到了一些问题。在Linux上使用system("title heartshape")和system("color XX")函数时,它会不断地显示此错误:
"sh: color:命令未找到“
代码中的第12行到第43行可以绘制心脏形状,在这个问题中没有用到,之后的for(;;)循环可以随着时间的推移不断地改变心脏形状的颜色。
源代码如下:
#include <math.h>
#include <stdlib.h>
#define I 20
#define R 340
int main(void)
{
int i, j, e;
int a;
long time;
system("title Heartshape");
/*codes that use to draw a heart, unhelpful to my question*/
for (i = 1, a = I; i < I / 2; i++, a--)
{
for (j = (int)(I - sqrt(I * I - (a - i) * (a - i))); j > 0; j--)
printf(" ");
for (e = 1; e <= 2 * sqrt(I * I - (a - i) * (a - i)); e++)
printf("\3");
for (j = (int)(2 * (I - sqrt(I * I - (a - i) * (a - i)))); j > 0; j--)
printf(" ");
for (e = 1; e <= 2 * sqrt(I * I - (a - i) * (a - i)); e++)
printf("\3");
printf("\n");
}
for (i = 1; i < 80; i++)
{
printf("\3");
}
printf("\n");
for (i = 1; i <= R / 2; i++)
{
if (i % 2 || i % 3)
continue;
for (j = (int)(R - sqrt(R * R - i * i)); j > 0; j--)
printf(" ");
for (e = 1; e <= 2 * (sqrt(R * R - i * i) - (R - 2 * I)); e++)
printf("\3");
printf("\n");
}
/*codes that use to change the color of the heart*/
for (;;)
{
system("color a");
for (time = 0; time < 99999999; time++);
system("color b");
for (time = 0; time < 99999999; time++);
system("color c");
for (time = 0; time < 99999999; time++);
system("color d");
for (time = 0; time < 99999999; time++);
system("color e");
for (time = 0; time < 99999999; time++);
system("color f");
for (time = 0; time < 99999999; time++);
system("color 0");
for (time = 0; time < 99999999; time++);
system("color 1");
for (time = 0; time < 99999999; time++);
system("color 2");
for (time = 0; time < 99999999; time++);
system("color 3");
for (time = 0; time < 99999999; time++);
system("color 4");
for (time = 0; time < 99999999; time++);
system("color 5");
for (time = 0; time < 99999999; time++);
system("color 6");
for (time = 0; time < 99999999; time++);
system("color 7");
for (time = 0; time < 99999999; time++);
system("color 8");
for (time = 0; time < 99999999; time++);
system("color 9");
for (time = 0; time < 99999999; time++);
}
return 0;
}这就是我项目的全部源代码。
代码可以在Windows编译器上完美地运行,但在Linux上继续显示错误sh: color: command not found。
在我对Linux仅有一周的有限经验中,我只能假设在c ++中使用system()时,Windows和Linux之间存在差异,而转义字符\3也不会在Linux上显示。
我已经找到了relevant question here,但这个问题似乎还没有解决,至少答案对我没有帮助。其他的答案似乎太复杂,无法解决这个问题。
我想知道使用函数system()的不同之处,以及在Linux上是否有持续改变心脏形状颜色的好方法?或者有其他的办法吗?
发布于 2022-08-12 20:36:38
问题不在于函数system(),尽管它在幕后做了不同的事情。当然,因为Windows和Linux是不同的操作系统。但是作为一个标准库函数,它通常在两个系统上都是这样做的:它允许操作系统的命令处理器执行内部命令或启动另一个程序。
问题在于您试图执行的程序(命令)。命令"title“和"color”对于我的shell (在Arch上的bash)是未知的,但是Windows ("cmd.exe")却知道这些命令。
一个类似的问题是您的'\3'输出。此特殊字符仅以外壳的特定字体显示。
你需要采取另一种方法。有几种可能的解决方案,例如使用"ncurses“作为独立于OS的库。
https://stackoverflow.com/questions/73338007
复制相似问题