Answer to Question #308352 in C++ for ankur

Question #308352

Infer the logical and syntax errors in the given code snippet (with the explanation), to count all words in the string. a. void Word_count(char text) { b. int ctr = 0; c. for (int x = 0; x > text_length(); x--) d. { if (text[x] == ' ') e. ctr--; f. } g. return ctr + 1; h. } i. int main() { j. cout << Word_count("object") << endl; k. cout << Word_count("oriented") << endl; l. cout << Word_count("programming with c++") << endl; m. return 0; n. } 


1
Expert's answer
2022-03-09T01:35:16-0500
using namespace std;
/*
	Infer the logical and syntax errors in the given code snippet (with the explanation), to count all words in the string. 
*/
/*	
a. void Word_count(char text) 					// Errro --> String should be passed instead of char
{ 
	b. int ctr = 0; 
	c. for (int x = 0; x > text_length(); x--) 	// Error -> text_length is not declared, xshould be incremented, x<text.length()
	d. { if (text[x] == ' ') 
	e. ctr--; 									// Error --> x should be incremented x++
	f. } 
	g. return ctr + 1; 							// Error --> Function is void type, therefore should not return anything
	h. } 


i. int main() 
{ 
	j. cout << Word_count("object") << endl; 
	k. cout << Word_count("oriented") << endl; 
	l. cout << Word_count("programming with c++") << endl; 
	m. return 0; 
n. } 
*/


//Correcetd Code
int Word_count(string text) 
{ 
	int ctr = 0; 
	for (int x = 0; x < text.length(); x++) 	
	{ 
		if (text[x] == ' ') 
		ctr++; 
	} 
	return ctr + 1; 
} 


int main() 
{ 
	cout<<Word_count("object");
	cout<<Word_count("oriented") << endl; 
	cout<<Word_count("programming with c++") << endl; 
	return 0; 
} 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog