Q:

C++ Strings | Find output programs | Set 2

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Strings (set 2).

Program 1:

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

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

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

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;
}

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;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

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.

Answer Program 2:

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.

Answer Program 3:

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());

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Strings | Find output programs | Set 3... >>
<< C++ Strings | Find output programs | Set 1...