Please explain c_str() and

while(key > 1){
key–; //why we did this?
}

1 Like

@Devansh_29 The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end.

Syntax:

const CharT* c_str() const
Parameter: The function does not accept any parameter

Return Value : The function returns a constant Null terminated pointer to the character array storage of the string.

Below is the implementation of the above function:

Program 1
// C++ code for illustration of
// basic_string::c_str function
#include <bits/stdc++.h>
#include
using namespace std;

int main()
{
// declare a example string
string s1 = “GeeksForGeeks”;

// check if the size of the string is same as the 
// size of character pointer given by c_str 
if (s1.size() == strlen(s1.c_str())) { 
    cout << "s1.size is equal to strlen(s1.c_str()) " << endl; 
} 
else { 
    cout << "s1.size is not equal to strlen(s1.c_str())" << endl; 
} 

// print the string 
printf("%s \n", s1.c_str()); 

}
Output:
s1.size is equal to strlen(s1.c_str())
GeeksForGeeks

1 Like

@Devansh_29 hey isme , while(key > 1){
key–; //why we did this?
}
Key jab tk 1 se bdi hai tab tk ye loop chlega aur andr loop ke k-- krrhe hai taki k jo hai 1 tk pahunch jaye aur loop khtm hojaye.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.