In: Computer Science
ceate a Visual Studio console project named exercise093. In the exercise093.cpp file first define a function void lowerToUpper(std::string & sentence) that iterates over all characters in the sentence argument. Any lowercase letter should be converted to uppercase. This can be done by including and testing each character in sentence with the islower() function. If islower(sentence[i]) returns true then sentence[i] should be replaced with toupper(sentence[i]). The main() function should assign "Hello how are you doing?" to sentence, call lowerToUpper(sentence), and use an if statement to check the new value of sentence. If the result is correct then main() should return 0 as usual. If the result is not correct then main() should display a descriptive error message (indicating the function called, argument and the incorrect result) on the console, and main() should return -1. This provides a unit test for the lowerToUpper() function. Finally, see what happens when you rerun the program after changing the function interface to void lowerToUpper(std::string sentence)
#include <iostream>
using namespace std;
void lowerToUpper(std::string &sentence){
int len = sentence.length();
for(int i=0; i<len; i++){
if(islower(sentence[i])){
string ch(1,
toupper(sentence[i]));
sentence.replace(i,1,ch);
}
}
}
int main() {
string sentence = "Hello how are you doing?";
lowerToUpper(sentence);
string temp = "HELLO HOW ARE YOU DOING?";
if(sentence==temp){
//You can remove this print statement. Used for demonstration
only.
cout<<"SUCCESS";
return 0;
}
else{
cout<<"Function lowerToUpper
did not correctly convert the string to uppercase.";
return -1;
}
}
After changing the function signature to void lowerToUpper(std::string sentence):
The reason behind this is that we have left the reference operator '&' in second function signature. So, it does not change the original string, original string remains the same, hece when we check for equality, it says false.