(1) Prompt the user to enter a string of their choosing. Output the string. (1 p
ID: 3594317 • 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<stdio.h>
#include <string.h>
//Returns the number of characters in usrStr
int GetNumOfCharacters(const char usrStr[]) {
/* Type your code here. */
}
int main(void) {
/* Type your code here. */
return 0;
}
Explanation / Answer
#include<stdio.h>
#include <string.h>
// as long as there are characters, incrementing i by 1 and returning the length
int GetNumOfCharacters(const char usrStr[]) {
int i=0;
for(i;usrStr[i];i++);
return i;
}
// checks if character is space or tab, if it doesn't then prints
void OutputWithoutWhitespace(const char usrSt[]){
int i=0;
while(usrSt[i])
{
if(usrSt[i] != ' ' && usrSt[i] != ' ')
printf("%c",usrSt[i]);
i++;
}
}
int main(void) {
// taking user input
char s[1000];
printf("Enter a sentence or phrase: ");
gets(s);
// printing whatever user entered
printf("You entered: %s ",s);
// calling length of string function
printf(" Number of characters: %d ",GetNumOfCharacters(s));
//calling function to print string without spaces and tabs
printf("String with no whitespace: ");
OutputWithoutWhitespace(s);
return 0;
}
/*SAMPLE OUTPUT
Enter a sentence or phrase: You entered: The only thing we have to fear is fear itself.
Number of characters: 46
String with no whitespace: Theonlythingwehavetofearisfearitself.
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.