Output ASCII value of character

2019-01-27 12:08发布

问题:

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout << "enter a character:";
    cin >> x;
    cout << "ASCII Value of " << x << "is" << string(x);
    return 0 ;
}

the error is

main.cpp||In function 'int main()':| 
main.cpp|10|error: invalid conversion from 'char' to 'const char*'| 
main.cpp|10|error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits,_Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'|
||=== Build finished: 2 errors, 0 warnings ===|

回答1:

std::cout << "ASCII Value of " << x << "is" << (int)x;

is one way (the cast circumvents the special treatement of a char type by the I/O stream library), but this will output your platform's encoded value of the character, which is not necessarily ASCII.

A portable solution is much more complex: You'll need to encode the ASCII set in a 128 element array of elements capable of storing a 7 bit unsigned value, and map x to a suitable element of that.



回答2:

There are 3 approaches to solving this problem:

  • Use to_string
  • Passing the correct value to cout
  • Using the std::string class correctly

The solutions are marked (numbers in comment).


Use std::to_string

Since 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.


Passing the correct value to cout

cout 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<int>(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. The T{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 notations T(e) and (T)e are neither safe nor general.

About conversions the C++ Core Guidelines specifies the following (among others)

  • ES.48: Avoid casts
  • ES.49: If you must use a cast, use a named cast
  • ES.64: Use the T{e}notation for construction

In this case I would suggest (3) or (4).


Using the std::string class correctly

string is a specialization of basic_string

using string = basic_string<char>;

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


回答3:

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout<< "enter a character:";
    cin>>x;
    cout<< "ASCII Value of "<< x<< "is"<< int(x);
    return 0 ;
} 

you mean return try this code



回答4:

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout<< "enter a character:";
    cin>>x;
    cout<< "ASCII Value of "<< x<< "is"<< char(x);
return 0 ;
}

try this its called return



标签: c++ ascii