In: Computer Science
Write a complete program using the do-while loop that prompts
the user to enter a string and displays its first and last
characters. Repeat until the user enter a string that contains only
one character.
Here is an example to show you how the output may look like:
<output>
Enter a string ( type only one character to exit): this is my
string
The first character is t
The last character is g
Enter a string ( type only one character to exit): _
<output>
Do the code in C++
Code:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;//variable declaration
while (true){
cout << "Enter a string:
";//prompt the user to enter a string
getline (cin, str);//take
input
//check and exit the loop if string
length is 1
if (str.length() ==1) {
break;
}
//if the above condition fails,
that is if the string lenght is greater than 1, the following
executes
else{
cout <<
"First letter: " << str[0] << "\nLast letter: "
<< str[str.length()-1] << "\n";
}
}
return 0;
}
Code in the image:
Please refer the following for indentation.
Output: