C++ Tutorial/Data Types/char pointer

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

Converting lowercase letters to uppercase letters using a pointer

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cctype>

using std::islower; using std::toupper; void f( char * ); int main() {

  char phrase[] = "characters";
  f( phrase );
  cout << phrase << endl;
  return 0;

}

void f( char *sPtr ) {

  while ( *sPtr != "\0" )
  {   
     *sPtr = toupper( *sPtr ); 
     sPtr++; 
  }

}</source>

CHARACTERS

Display value of char *, then display value of char static_cast to void *

<source lang="cpp">#include <iostream> using std::cout; using std::endl; int main() {

  char *word = "again";
 
  cout << "Value of word is: " << word << endl
     << "Value of static_cast< void * >( word ) is: " 
     << static_cast< void * >( word ) << endl;
  return 0;

}</source>

Value of word is: again
Value of static_cast< void * >( word ) is: 0x43e000

Printing a string one character at a time using a pointer

<source lang="cpp">#include <iostream> using std::cout; using std::endl; void f( const char * ); int main() {

  const char phrase[] = "a string";
  f( phrase );
  return 0;

} void f( const char *sPtr ) {

  for ( ; *sPtr != "\0"; sPtr++ )
     cout << *sPtr;

}</source>

a string

Printing the address stored in a char * variable

<source lang="cpp">#include <iostream> using std::cout; using std::endl; int main() {

  char *word = "again";
 
  cout << "Value of word is: " << word << endl
       << "Value of static_cast< void * >( word ) is: " 
       << static_cast< void * >( word ) << endl;
  return 0;

}</source>

Value of word is: again
Value of static_cast< void * >( word ) is: 0x43e000

Reverse string case using pointer arithmetic

<source lang="cpp">#include <iostream>

  1. include <cctype>

using namespace std;

int main() {

 char *p; 
 char str[80] = "This Is A Test"; 

 cout << "Original string: " << str << "\n"; 

 p = str; // assign p the address of the start of the array 


 while(*p) { 
   if(isupper(*p)) 
     *p = tolower(*p); 
   else if(islower(*p)) 
     *p = toupper(*p); 
   p++; 
 } 

 cout << "Inverted-case string: " << str; 

 return 0; 

}</source>

Original string: This Is A Test
Inverted-case string: tHIS iS a tEST