C++ only: Please implement a function that accepts a string parameter as well as two character arguments and a boolean parameter. Your function should return the number of times it finds the character arguments inside the string parameter. When both of the passed character arguments are found in the string parameter, set the boolean argument to true. Otherwise, set that boolean argument to false. Return -1 if the string argument is the empty string. The declaration for this function will be:
int findLetters( string s, char valueA, char valueB, bool & foundBoth );
Here are some examples of how a main routine could test this function:
char valueA = ‘9’;
char valueB = ‘0’;
bool b = false;
assert( findLetters( “Hello World”, valueA, valueB, b ) == 0
);
assert( b == false );
assert( findLetters( “9876543210”, valueA, valueB, b ) == 2
);
assert( b == true );
assert( findLetters( “999888777”, valueA, valueB, b ) == 3 );
assert( b == false );
assert( findLetters( “”, valueA, valueB, b ) == -1 );
assert( b == false );
Write the findLetters function.
Step 1 : Save the following code in AssertChar.cpp
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
int findLetters(string s, char valueA, char valueB, bool&
foundBoth) {
if (s.length() <= 0) {
return -1;
}
char ch;
int result = 0;
bool foundA = false;
bool foundB = false;
for (int i = 0, len = s.length(); i < len; i++) {
ch = s.at(i);
if (valueA == ch) {
result++;
foundA = true;
}
if (valueB == ch) {
result++;
foundB = true;
}
}
foundBoth = foundA && foundB;
return result;
}
int main(int argc, char** argv) {
char valueA = '9';
char valueB = '0';
bool b = false;
assert(findLetters("Hello World", valueA, valueB, b) ==
0);
assert(b == false);
assert(findLetters("9876543210", valueA, valueB, b) == 2);
assert(b == true);
assert(findLetters("999888777", valueA, valueB, b) == 3);
assert(b == false);
assert(findLetters("", valueA, valueB, b) == -1);
assert(b == false);
return 0;
}
It will compile and run without any error.
It will not produce any output since all assert() will succeed.
If it fails, please send me the error message.
Get Answers For Free
Most questions answered within 1 hours.