Answer to Question #308344 in C++ for stuti

Question #308344

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-10T02:08:46-0500

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;
} 

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