C++/Data Type/Char Array

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Char array and char pointer

   
#include <iostream>
using namespace std; 
int main(void){
   char *array = new char[256];
   char *target, *destination;
   
   int i;
   target = new char[256];
   for (i = 0; i < 256; i++) {
     array[i] = "A";
     target[i] = "B";
   }
   destination = new char[256];
   for (i = 0; i < 256; i++) {
     destination[i] = target[i];
     cout << destination[i] << " ";
   }
}


use char array as string

   
#include <stdio.h>
int main( )
{
 char        szmode1[4],             /* car   */
             szmode2[6];             /* plane */
 static char szmode3[5] = "ship";    /* ship  */
 szmode1[0] = "c";
 szmode1[1] = "a";
 szmode1[2] = "r";
 szmode1[3] = "\0";
 printf("\n\n\tPlease enter the mode �> plane ");
 scanf("%s",szmode2);
 printf("%s\n",szmode1);
 printf("%s\n",szmode2);
 printf("%s\n",szmode3);
 return(0);
}


Use cin.getline to read a char array based string

  
#include <iostream>
using namespace std;
int main()
{
  
 char name[25];
 cout << "Please enter your name \n";
 cin.getline(name,25);
 cout << "Hello " << name << endl;
 return 0;
}


use getline to read char array based string

  
#include <iostream>
#include <string >
using std::cout;  
using std::cin;
 
int main() 
{
  char s1[40],s2[40],s3[40];
  int size;
  cout << "Please enter a word \n";
  cin.getline(s1,40); 
  cout << "Please enter another word  \n";
  cin.getline(s2,40);
  size = strlen(s1);
     
  strcat(s1,s2);
  cout << "The length of the first string you entered is" << size << "\n";
  cout << "Both strings you entered are " << s3<< "\n";
  return 0;
}


Use new operator to allocate memory for char array

   
#include <iostream>
using namespace std; 
int main(void) {
   char *pointer;
   do {
     pointer = new char[10000];
     if (pointer)
       cout << "Allocated 10,000 bytes\n";
     else
       cout << "Allocation failed\n";
   } while (pointer);
}