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

23. (8 pts) Write a segment of code that: Prompts for and reads in a sentence en

ID: 3887502 • Letter: 2

Question

23. (8 pts) Write a segment of code that:

Prompts for and reads in a sentence ending in a question mark (?).

Determines and outputs the number of characters in the sentence (The ? is not part of the sentence)

Extracts and outputs a substring from the sentence starting at character position 8 and containing 6 characters

Assume that all header files have been declared, and use the following variable declarations only.

string sentence; // word read from standard input

string sub; // substring pulled from the sentence

string::size_type num; // number of characters

Explanation / Answer

#include<iostream>

#include<string>

using namespace std;

int main(){

string sentence; // word read from standard input

string sub; // substring pulled from the sentence

string::size_type num; // number of characters

cout<<"Enter a sentence ending with ? "<<endl;

getline(cin, sentence);

num = sentence.length();

sentence = sentence.substr(0,num-1);

cout<<"number of characters in the string is "<<sentence.length()<<endl;

// Extracts and outputs a substring from the sentence starting at character position 8 and containing 6 characters

sub = sentence.substr(7,6); // starting position is 8 as string index starts from 0 so first argument will be 8-1 = 7 and second argument will be length

cout<<sub;

// Remember if sub string is not long enough that it doesn't contain the 6 character after the 8th position then .substr return the possible number of character which are present

}

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