Home > front end >  type cast a char into string
type cast a char into string

Time:03-23

I am just curious the same type cast format works for char, int and maybe many others, but why it does not work for string, i.e., what's wrong with (string) 'c' behind the screen?

#include <iostream>
using namespace std;

int main(){
    char a = 'a';
    cout << (char) 99 <<endl;
    cout << (int) 'c'<<endl;
    cout<< (string) 'c'   "  " <<endl;  // why this does not work??? 
    cout<< string (1, 'c')   "  " <<endl;
    return 0;
}

CodePudding user response:

The problem is that there is no implicit conversion from an object of the type char to an object of the type std::string.

You could write for example:

 cout<< string( 1, 'c' )   "  " <<endl;

or

 cout<< string( "c" )   "  " <<endl;

or (using the C casting)

 cout<< ( string )"c"   "  " <<endl;

or

using namespace std::literals;

cout << "c"s   "  " << endl;

As you can see from this line

 cout<< string( 1, 'c' )   "  " <<endl;

there is used the constructor

basic_string(size_type n, charT c, const Allocator& a = Allocator());

CodePudding user response:

char, int, double, float, short, etc. are all integral types. They are "known" types in the language that have fixed sizes, fixed representations, and require no compilation for the compiler to understand. The compiler can convert one to another without much issue (aside from potential narrowing conversions that can lose data - like converting from a 16 bit integer to an 8 bit int).

std::string, on the other hand, is a class type. It cannot be directly understood by the compiler - the header file containing the class needs to be compiled and understood. This introduces several requirements, one of which is the need for a function to convert a type to your class. If you don't write a function to do this conversion, the compiler assumes one does not exist, and if you then try to use it, the compiler throws out an error.

Your third print here is asking the compiler to convert a char type to a std::string by invoking a cast function. This function does not exist, so the compiler throws a fit as a result.

Note that your fourth print does work because it calls a constructor function of std::string which takes a length and a char, which does exist.

CodePudding user response:

This doesn't work because std::string does not have a constructor that accepts a single char as argument. For example, this code compiles on g 9.3.0:

#include <iostream>
using namespace std;

class mystring : public string {
public:
  mystring(char c) :string({c}) {}
};

int main() {
  char a = 'a';
  cout << (char)99 << endl;
  cout << (int)'c' << endl;
  cout << (mystring)'c'   "  " << endl;
  cout << string(1, 'c')   "  " << endl;
  return 0;
}

Output:

c
99
c  
c  
  • Related