88.7k views
1 vote
What is the code to print out the third character in a string variable named str? A. cout << str[2]; B. cout << str(2); C. cout << str.at(2); D. cout << third(str);

User DJSunny
by
7.3k points

1 Answer

6 votes

Final Answer:

In C++, strings are zero-indexed, so `str[2]` correctly prints the third character of the string variable `str`. The correct option is A. `cout << str[2];`.

Step-by-step explanation:

In C++, strings are zero-indexed, meaning the first character is at index 0. Therefore, to access the third character, which is at index 2, you use square brackets `[]`.

Option A (`cout << str[2];`) correctly accesses the third character of the string variable `str` and prints it to the console. Options B and C are incorrect syntax for accessing elements in a string.

Option D is not a standard way to print the third character and lacks clarity compared to the correct option, A.

User Vivien Chevallier
by
6.5k points