Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following code fragment: string str1; str2; getline(cin,str1); a. W

ID: 3675474 • Letter: C

Question

Consider the following code fragment:

string str1; str2; getline(cin,str1);

a. Write a single-statement for loop that will output each character of str1 on a separate line as follows (e.g.) :

H

e

l

l

o

b. Write a for loop to construct a string, str2 that is exactly the same as str1 but without the last character. Use indexing and the length method only. Do not use any other functions.

c. Now write a single C++ statement that will accomplish the same thing as the previous problem using only the length and substr methods (i.e., do not use indexing or loops).

Explanation / Answer

a.

for (int i = 0; i < str1.length(); ++i) {

   cout << str1[i] << endl;

}

b.

for (int i = 0; i < str1.length() - 1; ++i) {

str2 += str1[i];

}

c.

str2 = str1.substr(0, str1.length() - 1);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote