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;
}
Answer Program 1:
Output:
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:
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:
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