0

I am currently writing a C++ program to control some LEDs by sending strings via termios to an Arduino. Each line is ended by a newline character. I have written a test program that would output to the terminal, but there are issues with the output of the following code snippet:

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);

This is my test input:

180
255
0
0

This is my expected output:

t255,0,0,180

And this is what I wind up with:

t
25,5
0,0,
184

Any help would be appreciated.

4

1 に答える 1

2

私には正しいように見えます。おそらく改行をスキップしたいと思っていましたfread()が、そうはしませんでした。FILE操作で行を読み取る必要がある場合は、fgets()ではなく. を使用しますfread()

于 2013-09-17T21:10:36.983 に答える