#include
using namespace std;
int main()
{
char x;
cout << \"enter a character:\";
cin >> x;
cout << \"ASCII Val
There are 3 approaches to solving this problem:
to_stringcoutstd::string class correctlyThe solutions are marked (numbers in comment).
std::to_stringSince C++11, there is function to convert numbers to a string (to_string):
/*(1)*/ std::cout << std::to_string( x );
There is no specialization for a char parameter. So the value is implictly converted.
coutcout would display the value of char object as a character.
If we want to output the value of a char object, we need to convert it to a type which is output by cout as a number instead of a character.
The C++ standard guarantees:
1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)
So any of those integer types can be used. Usually int is selected.
There are 4 conversions that can be used here:
1) Implicit - "Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2;"
/*(2)*/ int i = x;
std::cout << i;
2) Explicit - "Converts between types using a combination of explicit and implicit conversions."
/*(3)*/ std::cout << (int)x;
/*(4)*/ std::cout << int(x); // unsigned int(x) - is invalid,
// has to be a single-word type name
3) A named cast.
/*(5)*/ std::cout << static_cast(x);
4) Use the T{e} notation for construction
/*(6)*/ std::cout << int{x};
The
T{e}construction syntax makes it explicit that construction is desired. TheT{e}construction syntax doesn’t allow narrowing.T{e}is the only safe and general expression for constructing a value of type T from an expression e. The casts notationsT(e)and(T)eare neither safe nor general.
About conversions the C++ Core Guidelines specifies the following (among others)
In this case I would suggest (3) or (4).
std::string class correctlystring is a specialization of basic_string
using string = basic_string;
basic_string has many constructors.
There are only 2 constructors, which can take a predefined number of chars;
basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );Constructs the string with count copies of character ch. The behavior is undefined if count >= npos.
/*(7)*/ std::string s = std::string( 1, x );
basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() );Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if s does not point at an array of at least count elements of CharT, including the case when s is a null pointer.
/*(8)*/ std::string s = std::string( &x, 1 );