C/Data Type/Array Char

Материал из C\C++ эксперт
Версия от 10:22, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A simple dictionary

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
  char  *dic[][40] = {
      "A", "AA",
      "B", "BB",
      "C", "CC",
      "D", "DD",
      "", ""  /* null terminate the list */
  };
  char word[80]="A", ch;
  char **p;
  p = (char **)dic;
  do {
      if(!strcmp(*p, word)) {
        puts(" is ");
        puts(*(p+1));
        break;
      }
      if(!strcmp(*p, word)) {
          break;
      }
      p = p + 2;
  } while(*p);
  if(!*p){
      puts("Word not in dictionary.");
  }
  return 0;
}


Assign a value to an element inside a char array

  
#include <stdio.h>
int main(void)
{
  char str[80];
  *( str + 3) = "o";
  printf("%c", *(str+3));
  return 0;
}


Char array: assign value and loop

  
#include <stdio.h>
#include <conio.h>
int main(void)
{
  char str[80];
  int i;
  printf("Enter message (less than 80 characters)\n");
  for(i = 0; i < 80; i++) {
    str[ i ] = getche();
    if(str[ i ]=="\r") 
        break;
  }
  printf("\n");
  for(i = 0; str[ i ] != "\r"; i++) 
      printf("%c", str[i]+1);
  return 0;
}


Char array: pointer and loop

  
#include <stdio.h>
#include <string.h>
char *p[][2] = {
  "1", "red",
  "2", "yellow",
  "3", "red",
  "4", "green",
  "5", "yellow",
  "6", "red",
  "7", "red",
  "", "" /* terminate the table with null strings */
};
int main(void)
{
  int i;
  char value[80];
  printf("Enter value: ");
  gets(value);
  for(i = 0; *p[ i ][ 0 ]; i++) {
    if(!strcmp(value, p[ i ][ 0 ]))
      printf("%s is %s\n", value, p[ i ][ 1 ]);
  }
  return 0;
}


Compute the total of a list of numbers

#include <stdio.h>
int main()
{
    char  line[100];
    int   total;
    int   item;
    total = 0;
    while (1) {
        printf("Enter # to add \n");
        printf("  or 0 to stop:");
        fgets(line, sizeof(line), stdin);
        sscanf(line, "%d", &item);
        if (item == 0)
            break;
        total += item;
        printf("Total: %d\n", total);
    }
    printf("Final total %d\n", total);
    return (0);
}


contiguous array storage

  
#include <stdio.h>
#define iDAYS 7
int main()
{
 int index, iarray[iDAYS];
 printf("sizeof(int) is %d\n\n", (int)sizeof(int));
 for(index = 0; index < iDAYS; index++)
   printf("&iarray[%d] = %X\n", index,
           &iarray[index]);
 return(0);
}


For loop a char array

  
#include <stdio.h>
int main(void)
{
  char str[80];
  int i, spaces;
  printf("Enter a string: ");
  gets(str);
  spaces = 0;
  for( i = 0; str [ i ]; i++)
    if(str[i]==" ") 
        spaces++;
  printf("Number of spaces: %d", spaces);
  return 0;
}


For loop a char array using pointer

  
#include <stdio.h>
int main(void)
{
  char str[] = "Pointers are fun and hard";
  char *p;
  int i;
  p = str;
  /* loop until null is found */
  for(i = 0; p[ i ]; i++)
    printf("%c", p[ i ]);
  return 0;
}


how array addressing and pointer arithmetic are linked

#include <stdio.h>
#define ARRAY_SIZE 10

int main()
{
    char array[ARRAY_SIZE] = "123456789";
    int index;  /* Index into the array */
    for (index = 0; index < ARRAY_SIZE; ++index) {
        printf("&array[index]=0x%p (array+index)=0x%p array[index]=0x%x\n",
            &array[index], (array+index), array[index]);
    }
    return (0);
}


Loop and output a char array

  
#include <stdio.h>
int main(void)
{
  char str[80];
  int i;
  printf("Enter a string (less than 80 chars): ");
  gets(str);
  
  for(i = 0; str[i]; i++) 
      printf("%c", str[i]);
  return 0;
}


Output the address of char array

  
main () {
    
  char * s1 = "aaa";
  char s2[] = "vvv";
    
    printf(" %16lu \n", s1, s1); 
    printf(" %16lu \n", s2, s2);
  s1 = s2;
    
    printf(" %16lu \n", s1, s1);
    printf(" %16lu \n", s2, s2);
}


Show how bitmapped graphics may be used

#include <stdio.h>
#define X_SIZE 40
#define Y_SIZE 60
char graphics[X_SIZE / 8][Y_SIZE];   /* the graphics data */
void print_graphics(void);
#define SET_BIT(x,y) graphics[(x)/8][y] |= (0x80 >>((x)%8))
int main()
{
    int loc;
    int x;
    int y;
    for (y = 0; y < Y_SIZE; ++y) {
        for (x = 0; x < X_SIZE / 8; ++x) {
            graphics[x][y] = ".";
        }
    }

    for (loc = 0; loc < X_SIZE; ++loc)
        SET_BIT(loc, loc);
    print_graphics();
    return (0);
}
void print_graphics(void)
{
    int x;
    int y;
    int bit;
    for (y = 0; y < Y_SIZE; ++y) {
        for (x = 0; x < X_SIZE / 8; ++x) {
            for (bit = 0x80; bit > 0; bit = (bit >> 1)) {
                if ((graphics[x][y] & bit) != 0){
                    printf("*");
                }else{
                    printf("%c",graphics[x][y]);
                }
            }
        }
        printf("\n");
    }
}


the use of strings

  
#include <iostream>
using namespace std;
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";
 cout << "\n\n\tPlease enter the mode �> plane ";
 cin >> szmode2;
 cout << szmode1 << "\n";
 cout << szmode2 << "\n";
 cout << szmode3 << "\n";
 return(0);
}


Tic-Tac-Toe

#include <stdio.h>
void main()
{
  int i = 0;                                   /* Loop counter                         */
  int player = 0;                              /* Player number - 1 or 2               */
  int go = 0;                                  /* Square selection number for turn     */
  int row = 0;                                 /* Row index for a square               */  
  int column = 0;                              /* Column index for a square            */
  int line = 0;                                /* Row or column index in checking loop */
  int winner = 0;                              /* The winning player                   */
  char board[3][3] = {                         /* The board                            */
                       {"1","2","3"},          /* Initial values are reference numbers */
                       {"4","5","6"},          /* used to select a vacant square for   */
                       {"7","8","9"}           /* a turn.                              */
                     };
   /* The main game loop. The game continues for up to 9 turns */
   /* As long as there is no winner                            */
   for( i = 0; i<9 && winner==0; i++)
   {
      /* Display the board */
    printf("\n\n");
      printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
      printf("---+---+---\n");
      printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
      printf("---+---+---\n");
      printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);
      
      player = i%2 + 1;                           /* Select player */
 
      /* Get valid player square selection */
      do
      {
         printf("\nPlayer %d, please enter the number of the square "
       "where you want to place your %c: ", player,(player==1)?"X":"O");
         scanf("%d", &go);
         row = --go/3;                                 /* Get row index of square      */
         column = go%3;                                /* Get column index of square   */
      }while(go<0 || go>9 || board[row][column]>"9");
      board[row][column] = (player == 1) ? "X" : "O";        /* Insert player symbol   */
      /* Check for a winning line - diagonals first */     
      if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) ||
         (board[0][2] == board[1][1] && board[0][2] == board[2][0]))
        winner = player;
      else
      /* Check rows and columns for a winning line */
        for(line = 0; line <= 2; line ++)
          if((board[line][0] == board[line][1] && board[line][0] == board[line][2])||
             (board[0][line] == board[1][line] && board[0][line] == board[2][line]))
            winner = player;
      
   }
   /* Game is over so display the final board */
   printf("\n\n");
   printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
   printf("---+---+---\n");
   printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
   printf("---+---+---\n");
   printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);
   /* Display result message */
   if(winner == 0)
      printf("\nHow boring, it is a draw\n");
   else
      printf("\nCongratulations, player %d, YOU ARE THE WINNER!\n", winner);
}


verifying array initialization

  
#include <stdio.h>
#define iGLOBAL_ARRAY_SIZE 10
#define iSTATIC_ARRAY_SIZE 20
int iglobal_array[iGLOBAL_ARRAY_SIZE];          /*a global array*/
int main( ){
 static int istatic_array[iSTATIC_ARRAY_SIZE]; /*a static array*/
 printf("iglobal_array[0]: %d\n",iglobal_array[0]);
 printf("istatic_array[0]: %d\n",istatic_array[0]);
 return(0);
}