0

我目前正在编写一个 C++ 程序,通过 termios 向 Arduino 发送字符串来控制一些 LED。每行以换行符结束。我编写了一个可以输出到终端的测试程序,但是以下代码段的输出存在问题:

char* ledAddr = (char*)malloc(3);
char* rVal = (char*)malloc(3);
char* gVal = (char*)malloc(3);
char* bVal = (char*)malloc(3);
...
fread(ledAddr, 3, 1, stdin);
fread(rVal, 3, 1, stdin);
fread(gVal, 3, 1, stdin);
fread(bVal, 3, 1, stdin);
...
char* outputString = malloc(17);

outputString[0] = 't';
strncpy(outputString+1, rVal, 3);
outputString[4] = ',';
strncpy(outputString+5, gVal, 3);
outputString[8] = ',';
strncpy(outputString+9, bVal, 3);
outputString[12] = ',';
strncpy(outputString+13, ledAddr, 3);
outputString[16] = '\n'

fwrite(outputString, 17, 1, stdout);

这是我的测试输入:

180
255
0
0

这是我的预期输出:

t255,0,0,180

这就是我的结论:

t
25,5
0,0,
184

任何帮助,将不胜感激。

4

1 回答 1

2

Looks correct to me. You probably wanted to skip the newlines but fread() won't do that for you. If you wanted the FILE operations to read lines, you'd use fgets() rather than fread().

于 2013-09-17T21:10:36.983 回答