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. }
Errors:
No headers were included.
a. The function accepts a pointer to char not char
b. Function to get a length of the string is strlen(text), not text_length()
b. Also the variable x should increase not decrease every loop step.
e. The counter ctr should increase, not decrease
#include <cstring>
#include <iostream>
using namespace std;
int Word_count(char* text) { // a
int ctr = 0; // b
for (int x = 0; x < strlen(text); x++) // c
{ if (text[x] == ' ') // d
ctr++; // e
} // f
return ctr + 1; // g
} // h
int main() {
cout << Word_count("object") << endl;
cout << Word_count("oriented") << endl;
cout << Word_count("programming with c++") << endl;
return 0;
}
Comments
Leave a comment