Char Array Basics


  • The size of char data type is 1 Byte in C++ and 2 bytes in Java. In C++, char is defined as 1 byte by the language specification.
  • The preferred method to read a string with whitespaces in C++ isΒ std::getline((std::cin, string)). This is defined in theΒ <string>header.
  • std::stringΒ class is preferred over C-style character arrays because it provides many useful member functions for common string operations.
#include<iostream>
#include <string>
using namespace std:
 
int main(){
	
	// Character arrays 
	char arr[100];
	
	// Assigning Values
	arr[0] = 'a';
	arr[1] = 'b';
	arr[2] = 'c
	arr[3] = '\0';
	
	cout << arr[0] << endl;
	cout << arr[1] << endl;
	cout << arr[2] << endl;
	
	cout << arr << endl; // will give content of array rather than the address of the array 
	// Special functionality of the character array
	
	// For getting the address of the character array 
	char * ptr = arr;
	cout << ptr << endl; //abc
	cout << (void *)ptr << endl; // address 
	
	// More ways to create a character array 
	char b[] = {'x', 'y', 'z', '\0'} // Character array must be null terminated
	cout << sizeof(b) << endl; // 4 byte
	cout << b << endl; //xyz
	
	// Another way
	char c[] = "hello"; // Double quotes means null terminated array
	cout << sizeof(c) << endl; // 6 byte
	cout << c << endl; //hello
	
	return 0;
}

Strlen and Strcpy


The strlen() and strcpy() functions operate on null-terminated C-style strings. With C++ strings, equivalent functionality is provided through member functions:

#include<iostream>
#include <string>
using namespace std:
 
int main(){
	
	// Char array Creation & Printing
	char arr[100] = "hello";
	
	// assign some new value inside it
	//strcpy(dest, src);
	strcpy(arr, "hi everyone");
	
	// length
	cout << "Length of string is " << strlen(arr) << endl; // 11
	cout << "Size of array is " << sizeof(arr) << endl; // 100
	
	// Print 
	cout << arr << endl;
	
	return 0;
}

Input using Cin.GetLine


The cin.getline() function is used to read an entire line of input from the user, including spaces. This is in contrast to the cin >> operator which only reads a single word at a time.

Some key properties of cin.getline():

  • It takes the input character array and max length as parameters:
char arr[100];
cin.getline(arr, 100); 
  • By default it stops reading input at the newline β€˜\n’ character. This allows it to read an entire line.

  • An optional 3rd parameter can specify a different delimiter:

cin.getline(arr, 100, '$');

Now the input will stop at ’$’ instead of newline.

  • Input is stored in the array along with the delimiter. So array size should account for that extra character.

  • The newline β€˜\n’ input also gets stored in the array. So a max length of 100 can actually only store 99 characters.

  • A null terminator β€˜\0’ is automatically added after the input.

Here is example code demonstrating cin.getline() to read line input:

char name[100];
cin.getline(name, 100); //reads a name
 
char sentence[1000];
cin.getline(sentence, 1000, '.'); //reads sentence ending in '.'

TIP

cin.getline() is the preferred method in C++ to read entire lines including space separated words. The parameters allow handling delimiters and max array size.

Input using Cin.Get


The cin.get() function in C++ is used to read a single character input from the user.

Some key properties of cin.get():

  • It reads and returns the next character immediately available in the input stream.

  • It can read whitespace characters like space ’ ’ and newline β€˜\n’ which are ignored by cin >>.

  • The returned character can be stored in a char datatype:

char ch;
ch = cin.get();
  • An IF check can then be used to take action based on the input character:
if(ch == ' ') {
  // user entered space
} else if(ch == '\n') {
  // user entered newline 
} else {
  // user entered regular character
}
  • stdin stream state is maintained, so cin.get() picks up right where previous input functions left off.

  • Useful for taking precise character level input, or checking for specific delimiter keys.

Here is some sample code showing usage of cin.get():

char ch;
cout << "Enter any character: "; 
 
ch = cin.get(); //get input  
 
if(ch >= 'a' && ch <= 'z') {
  cout << "You entered: " << ch << endl;
} else {
  cout << "Not an alphabet" << endl; 
}

TIP

cin.get() allows reading direct single character input in C++ and applying customized logic based on the input.

String Length


The C++ library provides the strlen() function to get the length of a null-terminated string. However, we can also create our own string length functionality.

Here is an example custom length() function to find the length of a char array:

#include<iostream>
#include <string>
using namespace std:
 
int length(char *arr) {
 
  int count = 0;
 
  while(arr[count] != '\0') {
    count++; 
  }
 
  return count;
 
}
 
int main() {
 
  char arr[100] = "hello";
  
  int len = length(arr); // len = 5
 
  return 0;
 
}

The key aspects of this function:

  • It accepts the character array as a parameter
  • Initializes a count variable to track length
  • Iterates through array until null terminator \0 is reached
  • Returns the final count value

We can compare this to the built-in strlen():

int len = strlen(arr); // len = 5

TIP

While strlen() is preferred, a custom length() shows how string lengths can be determined by iterating through arrays until the null termination.

Readline


The C++ library provides cin.getline() to read an entire line from input. However we can create our own custom readline() functionality as well for learning purposes.

Here is an example implementation:

#include<iostream>
#include <string>
using namespace std:
 
// Create a function to read character array without using library functions such as cin.getline
void readLine(char * arr, int len, int delim){
	// line terminates at '\n'
	// Read + Store array 
	int cnt = 0;
	char ch;
	while(true){
		ch = cin.get();
		arr[cnt] = ch;
		
		if(cnt==len-1 || ch==delim){
			break;
		}
		cnt++; 
	}
	// terminates the array also with a null character 
	arr[cnt] = '\0';
	cout << cnt << endl;
}
 
int main(){
	
	char arr[10];
	readLine(arr, 10, 'n');
	cout << arr << endl;
	cout << strlen(arr) << endl;
	
	return 0;
}

The key aspects are:

  • It takes in the character array, max length, and an optional custom delimiter
  • Reads input character-by-character usingΒ cin.get()Β in a loop
  • Checks if delimiter reached or array is filled
  • Sets array end to null terminator

Using default newline delimiter, it replicates cin.getline() functionality of reading entire line as input.

Largest string example


#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
 
  // Read number of strings
  int n;
  cin >> n;
  
  // Consume newline
  cin.ignore();
  
  // Track largest string
  string largest;
  
  // Track length of largest string
  int maxLen = 0; 
  
  // Read n strings
  for(int i = 0; i < n; i++) {
  
    string current;
    getline(cin, current);
    
    // Update largest string if current string is longer
    if(current.length() > maxLen) {
      largest = current;
      maxLen = current.length();
    }
    
  }
 
  // Print result
  cout << "Largest String: " << largest << endl;
  cout << "Length: " << maxLen << endl;
 
  return 0;
}

Notes:

  • Use C++ strings instead of C-style character arrays
  • getline(cin, string)Β reads a line including spaces
  • AccessΒ .length()Β member function instead ofΒ strlen()
  • No need to manually copy strings, just assign strings naturally