(1) Prompt the user to enter a string of their choosing. Output the string. (1 p
ID: 3938664 • Letter: #
Question
(1) Prompt the user to enter a string of their choosing. Output the string. (1 pt)
Ex:
(2) Complete the GetNumOfCharacters() function, which returns the number of characters in the user's string. We encourage you to use a for loop in this function. (2 pts)
(3) In main(), call the GetNumOfCharacters() function and then output the returned result. (1 pt)
(4) Implement the OutputWithoutWhitespace() function. OutputWithoutWhitespace() outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is ' '. Call the OutputWithoutWhitespace() function in main(). (2 pts)
Ex:
#include <iostream>
#include <string>
using namespace std;
//Returns the number of characters in usrStr
int GetNumOfCharacters(const string usrStr) {
int count = 0;
char ch;
for(int i=0; i<usrStr.length(); i++){
ch = usrStr.at(i);
count++;
}
return count;
}
string OutputWithoutWhitespace(const string usrStr ){
char ch;
string s;
for(int i=0; i<usrStr.length(); i++){
ch = usrStr.at(i);
if(ch !=' '){
s = s + ch;
}
}
return s;
} /* Type your code here. */
}
int main() {
string s;
cout << "Enter a sentence or phrase: ";
getline(cin , s);
cout<<"You entered: "<<s<<endl;
cout<<"Number of characters: "<<GetNumOfCharacters(s)<<endl;
cout<<"String with no whitespace: "<<OutputWithoutWhitespace(s)<<endl; /* Type your code here. */
return 0;
}
Explanation / Answer
Hi your code was working fine except for the fourth part. And there's just a small change(in Bold below). Hope your problem is solved!
#include <iostream>
#include <string>
using namespace std;
//Returns the number of characters in usrStr
int GetNumOfCharacters(const string usrStr) {
int count = 0;
char ch;
for(int i=0; i<usrStr.length(); i++){
ch = usrStr.at(i);
count++;
}
return count;
}
string OutputWithoutWhitespace(const string usrStr ){
char ch;
string s;
for(int i=0; i<usrStr.length(); i++){
ch = usrStr.at(i);
if(ch !=' ' && ch!=' '){
s = s + ch;
}
}
return s;
} /* Type your code here. */
int main() {
string s;
cout << "Enter a sentence or phrase: ";
getline(cin , s);
cout<<"You entered: "<<s<<endl;
cout<<"Number of characters: "<<GetNumOfCharacters(s)<<endl;
cout<<"String with no whitespace: "<<OutputWithoutWhitespace(s)<<endl; /* Type your code here. */
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.