In: Computer Science
Using c++, write a program that reads a sequence of characters
from the keyboard (one at a
time) and creates a string including the distinct characters
entered and displays the
string on the screen. The input terminates once the user enters a
white-space
character or the user has entered 50 distinct characters.
Do not use C-Strings.
2. Use the following function to append character “ch” to the
string “s”:
s.push_back(ch);
3. Read the input characters one by one, i.e. do not read the input
as a string.
4. Do not use arrays.
The required C++ code is as follows:----
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
string s; // String to store the characters
s="";
char ch;
while(s.length()!=50) // Checking whether the length of string is 50 or not
{
cout<<"Enter a character"<<endl; // Prompt the user to enter the next character
cin>>ch;
if(isspace(ch)) // isspace (char ch) is a function in C which checks if the character passed as an argument is a whitespace character or not
break; // Break out of loop if character entered is a whitespace character...
bool found=false; // variable to check if the recently entered character is a distinct character or not
for (int i=0;i<s.length();i++) // Loop to check if the recently entered character is already present in the string or not
{
if(s[i]==ch)
found=true;
}
if(!found) // If the character is distinct we append it to the string...automatically length of string increases by 1..
s.push_back(ch); // We push the recently entered distinct character at the end of the string..
}
if(s.length())
cout<<"The resultant string is --- "<<s<<endl;
else
cout<<"The resultant string is an empty string"<<endl; // Case when the first character entered by the user is a whitespace character
}