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. }
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;
}
Comments
Leave a comment