November 18, 2022

String snd Boolean

Posted on November 18, 2022  •  2 minutes  • 253 words

1. Boolean

  1. bool is a data type which can hold the values true or false.

Syntax:

bool varName = value;

Example:

#include <iostream>

int main()
{
    bool varName1 = true;
    bool varName2 = false;

    std::cout << varName1 << std::endl;
    std::cout << varName2 << std::endl;

    int age;
    std::cout << "Enter your age:";
    std::cin >> age;

    bool isGreater18 = age >= 18;
    std::cout << "isGreater18: " << isGreater18;
}

link

2. String

  1. String is a collection of characters (char).

Defining String in C++

  1. C-Style string char[] (simple character array).

  2. Standard library string class.

1. C-Style String

Syntax 1:

char varName[] = "string";

Syntax 2:

char varName[10] = "string";

where varName is a string variable containing 7 characters ( 6 + 1 \0 ).

Note that \0 is the last character added automatically.

Example:

#include <iostream>

int main()
{
    char stringVar[] = "#anooptube";
    char name[] = {'a','n','o','o','p','\0'};
    char state[7] = {'k','e','r','a','l','a','\0'};
}

2. Standard string class

standard library privides a string class with useful functionalities.

Syntax:

std::string stringVar = "string";

Example:

#include <iostream>

int main()
{
    std::string stringVar = "#anooptube";
}

How to read and write string

Example:

#include <iostream>

int main() {
  std::cout << "Enter your name1:";
  std::cin >> name;

  std::cin.ignore(1000, '\n');

  std::cout << "Enter your name2:";
  std::getline(std::cin, name1);

  std::cout << name << std::endl;
  std::cout << name1 << std::endl;
}

where

  1. std::cin.ignore(1000, '\n'); is used to clear the input buffer.

  2. std::cin only read single word (space is used as terminating character).

  3. std::getline() is used to read a line of text from the console.

Follow me

I work on everything coding and share developer memes