1

I'm writing a QT Console Application to write out of an FTDI cable using the QSerialport library. (the FTDI cable is connected to a logic analyzer so I can debug the output)

I need to pass int x = 255; to the line myserial->putChar();

I tried to convert the int to a char using:

int x = 255; std::string s = std::to_string(x); char const *myChar = s.c_str(); myserial->putChar(myChar);

and received the error:

cannot initialize a parameter of type 'char' with an lvalue of type 'const char*'

However in this test starting with a char everything works perfectly:

char myChar = 255; myserial->putChar(myChar);

Giving the correct result of 0xFF on the logic analyzer.

Can anyone help? Thanks!

88877
  • 485
  • 3
  • 11
M. P.
  • 91
  • 2
  • 10

4 Answers4

1

Just do it:

int x = 255;
mySerial->putChar(x);

The compiler will convert the argument for you. Unless you have some additional requirement that you haven't mentioned you could make it even simpler:

mySerial->putChar(255);
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

This should work:

unsigned int x = 255;
myserial->putChar( static_cast<char>(x) );
nshct
  • 1,197
  • 9
  • 29
0

Your call to s.c_str() returns a C-string. In this case the string only contains a single characters, but that is not the same as a character variable! A C-string is a contiguous sequence of characters terminated with the null character, '\0'. What you are trying to pass to putChar is a pointer to the first character of this array.

As suggested by several other posters, you need to use a cast: putChar( static_cast<char>(x) ).

Harry Braviner
  • 627
  • 4
  • 12
0

Your first code didn't work because because std::to_string(255) will give you : std::string("255") so with your c_str conversion, your code is the same as: myserial->putChar(50);.

Answer given by Naschkatze is certainly a better approach.

P. Brunet
  • 204
  • 1
  • 8