Lesson 4 – C++ Char Type, String Type

Spread the love

Diving into the c++ char type. This very small memory type holds enough space for 1 English type character.

Below x is a single char. However, y is an array of chars. Both c and c++ have several ways of expressing an array of chars.


char x = ‘C’;

char y[7] = {‘C’,’h’,’e’,’r’,’r’,’y’,’\0′};


/* We look at the char type 
   that holds single characters
   Programmer: Jane Doe
   Date : May 2020
*/
  
#include <iostream>
  
using namespace std;
  
int main(){
   char s;
   s = 'C';
   cout << "Sending a single character to the console\n";
   cout << s;
}

Can a c++ char character type hold a String? Why not?


// Looking at whether a char can hold a string
#include <iostream>
  
using namespace std;
  
int main(){
   char s;
   s = 'Coding Foolz';
   cout << "Outputs a single character to the console\n";
   cout << s;
}
/* No coding syntax error and outputs
   "Outputs a single character to the console"
   z 
   and not 'Coding Foolz'
*/


So, what went wrong here?

I could spend 5 paragraphs writing about this but let me be brief.

A c++ char is not a string, it is just 2 bytes that hold just 1 Ascii Character

s=’Coding Foolz’ either requires that we use a string type like

string s = “Coding Foolz”

or requires that we use an array of chars like this with a null character at the end. Yes, that is what the ‘\0’ means.

char y[7] = {‘C’,’h’,’e’,’r’,’r’,’y’,’\0′};


#include <iostream>
  
using namespace std;
  
int main(){
   //char s;
   char s[] = "Coding Foolz";
   cout << "Outputs a string to the console\n";
   cout << s;
}

// No coding syntax error and outputs
// Outputs the string to the console
// Coding Foolz


Note the flexibility of “cout << “ that we sometimes take for granted. So far “cout <<“ has adroitly handled int, char, double and string without complaint


Next Lesson 5 -> Booleans and Flow Control

Top