Home »
C++ programming »
C++ find output programs
C++ Strings | Find output programs | Set 3
This section contains the C++ find output programs with their explanations on C++ Strings (set 3).
Submitted by Nidhi, on July 18, 2020
Program 1:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string str = "includehelp";
char c_str[15];
strcpy(c_str, str.c_str());
cout << c_str;
return 0;
}
Output:
includehelp
Explanation:
Here, we created the string object str, which is initialized with string "includehelp", And we created character array c_str with size 15.
strcpy(c_str,str.c_str());
Here, we used c_str() member function of the string class, which is used to convert a string object into a character array. Then we copy the resulted character array into the c_str()character array, and then we finally print the c_str that will print "includehelp" on the console screen.
Program 2:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "includehelp";
for (int i = 0; i < str.length(); i++)
cout << str.charAt(i) << " ";
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:11:21: error: ‘std::string
{aka class std::basic_string}’ has no member named ‘charAt’
cout << str.charAt(i) << " ";
^~~~~~
Explanation:
It will generate a syntax error. because charAt() is not a member function of class string. The at() member function of string class is used to get characters index-wise from the string.
Program 3:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "includehelp";
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.at(i) - 32;
cout << ch << " ";
}
return 0;
}
Output:
I N C L U D E H E L P
Explanation:
Here, we created a string str initialized with "includehelp" and we create a character variable ch. Here, we accessed character index-wise from string str, and we subtract each character by 32. Then each character will convert into uppercase.
Let's understand how it works? Here, the subtraction will work on ASCII values. The ASCII value of small 'i' is 105, after subtraction, the value will be 73, and we know that the 73 is the ASCII value of capital 'I', just like that all character will convert into uppercase.
Then finally "I N C L U D E H E L P" will be printed on the console screen.