In: Computer Science
C++, Write a function, noPunct, that would take a string, go through the string character by character, and push any character that is NOT a punctuation mark onto a stack but count the punctuation dropped. After going through the entire string, print the contents of the stack. Then print the number of punctuation dropped.
Hint: use ispunct() library function (returns true if character is punctuation)
Note: Variable names and object names are used arbitrarily. These can be changed according to the user's choice. Please refer to code snippets for a better understanding of comments and indentations.
IDE Used: Dev C++
Program Code
#include <iostream>
#include <string>
#include <ctype.h>
#include <bits/stdc++.h>
using namespace std;
// function that will take input string
// and display number of punction dropped
void noPunct(string inp_stg )
{
// declare stack obkect
stack <char> char_stack;
// count number of punctuation
int num_punc = 0;
// check each character of the input string
for(int itr = 0; itr < inp_stg.length();
itr++)
{
// check if character is a
punctuation mark
if(ispunct(inp_stg[itr]))
{
// if yes then
increment punctuation counter
num_punc++;
}
else
{
// if not then
push the character to the stack
char_stack.push(inp_stg[itr]);
}
}
// show the content of the stack
cout<<"\nContent of the stack\n";
while (!char_stack.empty())
{
cout<<" "<<char_stack.top();
char_stack.pop();
}
// show the number of punctuation dropped
cout<<"\nNumber of punctuation marks dropped :
"<<num_punc;
}
// main function
int main()
{
// input string
string inp_stg;
// prompt user to input the string
cout<<"Input string to read : ";
// read the string
getline(cin, inp_stg);
// call the function
noPunct(inp_stg);
return 0;
}
Code Snippets
Sample Output