Reputation: 21
I want to write like this:
int x;
cin >> x;
if (x == 10) {
x = "A";
}
But I get this error message "error: invalid conversion from 'const char*' to 'int'"
Upvotes: 0
Views: 82
Reputation: 84642
From your comment below the first answer, if you are converting to a hexadecimal string, you can do it directly with std::sprintf()
and a plain old C-string. See std::printf, std::fprintf, std::sprintf, std::snprintf. You can do:
#include <iostream>
#define MAXHEXSTR 36
int main (void) {
uint16_t u = 65535;
char hexstr[MAXHEXSTR] = "";
std::sprintf (hexstr, "0x%04x", u);
std::cout << hexstr << '\n';
}
You can adjust the format string to meet your needs. Above it just formats the 16-bit value with a "0x"
prefix and the conversion yields a 4-byte hex representation of the value zero padded as needed.
Example Use/Output
$ ./bin/hexstrprintf
0xffff
or
A value of ten would yield:
$ ./bin/hexstrprintf
0x000a
Let me know if you have further questions.
Upvotes: 0
Reputation: 56
C++ has something called type checking, which basically means that you can't change the type of a variable (so if you define x
as an int, you can't redefine it to a string). If you want to save the value of x
as a string, you could do the following:
int x = 5;
std::string xAsString = std::to_string(x);
As a side note, you should use ==
in your if-statement to check whether two things are equal.
Upvotes: 3