Initializing and Reading C Style Strings


//  this program demonstrates several ways to initialize and read C style strings

#include <iostream.h>

const int MAX = 21;
int main()
{
   int i;

//  null byte automatically added to end when you initialize with double
//  quotes; if you don't specify size, it is chosen to fit chars entered

   char being[] = "To be, or not to be";

//  you must add null byte and make sure there is room for it when you
//  initialize each element of the array separately

   char ending[8] = {'T','h','e',' ','E','n','d','\0'};

   char soft[20];
   char line[MAX];

//  you must add null byte and make sure there is room for it when you
//  assign to each element of the array separately

   soft[0] = 'B';
   soft[1] = 'u';
   soft[2] = 't';
   soft[3] = ',';
   soft[4] = ' ';
   soft[5] = 's';
   soft[6] = 'o';
   soft[7] = 'f';
   soft[8] = 't';
   soft[9] = '\0';

//  display the strings defined above, surrounded by *'s

   cout << "being: ***" << being << "***" << endl;
   cout << "ending: ***" << ending << "***" << endl;
   cout << "soft: ***" << soft << "***" << endl;

//  get will read one char; use a loop to read a whole string
//  get will not add the null byte

   cout << "Enter a string: ";
   i = 0;
   line[0] = cin.get();
   while (line[i] != '\n' && i < MAX-1)
   {
      i++;
      line[i] = cin.get();
   }
   line[i] = '\0';
   cout << "line: ***" << line << "***" << endl;

//  getline will read up to newline, but will not read more than MAX-1
//  chars and will add null byte

   cout << "Enter a string: ";
   cin.getline(line,MAX);
   cout << "line: ***" << line << "***" << endl;

//  getline will read up to char 'x', but will not read more than MAX-1
//  chars and will add null byte

   cout << "Enter a string: ";
   cin.getline(line,MAX,'x');
   cout << "line: ***" << line << "***" << endl;

}

Output


being: ***To be, or not to be***
ending: ***The End***
soft: ***But, soft***
Enter a string:      here now
line: ***     here now***
Enter a string: first try
line: ***first try***
Enter a string:     try again  x
line: ***    try again  ***


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002