C++ Strings | Find output programs | Set 2

This section contains the C++ find output programs with their explanations on C++ Strings (set 2).
Submitted by Nidhi, on July 16, 2020

Program 1:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str[] = { "ABC", "PQR", "LMN", "XYZ" };

    cout << str[-EOF - EOF];
    return 0;
}

Output:

LMN

Explanation:

Here, we created an array of strings that contains 4 strings "ABC", "PQR", "LMN" and "XYZ".

Consider the below cout statement,

cout<>str[-EOF-EOF];

Here the value of EOF is -1. Then

	str[-EOF-EOF]
	str[--1-1]
	str[--2]
	str[2]

Then the value of str[2] is "LMN" that will be printed on the console screen.

Program 2:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str[] = { "ABC", "PQR", "LMN", "XYZ" };
    int len = 0;

    len = (str[1].size() + str[2].length()) / 3;

    cout << str[len];

    return 0;
}

Output:

LMN

Explanation:

Here, we created an array of strings. And a local variable len initialized with 0. In C++, both size() and length() functions are used to get the length of the string in terms of bytes.

Let's understand the expression.

len = str[1].size()+str[2].length()/3;
len = (3+3)/3;
len = 6/3;
len = 2;

Then the value of the 2nd index that is "LMN" will be printed on the console screen.

Program 3:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;

int main()
{
    string str[] = { "ABC", "PQR", "LMN", "XYZ" };
    int len = 0;

    len = strlen((char*)str[2]);

    cout << str[len];

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:11:30: error: invalid cast from type ‘std::string {aka std::basic_string}’ to type ‘char*’
     len = strlen((char*)str[2]);
                              ^

Explanation:

It will generate syntax error because the strlen() function cannot get the length of the string object. Here we need to convert a string object into the character array. The c_str() function of string class is used to convert the object of the string into a character array.

So that we need to below statement to find the length of the string.

len = strlen(str[2].c_str());





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.