I am trying to complete pset2 Readability and have a doubt on counting words. Can this be an approach?

int words = 0;
for (int i = 0; i< n; i++)
    if (isblank(text[i]))
printf("%i word(s)\n", words + 1);

Since there are more words than spaces I wrote "words + 1" on the printf function, but for some reason it doesn't seem right. Thanks for the help, I am really struggling with these problem sets!


I'd test exactly for a space (ie text[i] == ' ') rather than isblank and adding 1 at the end is expected, since if you have text like "Hello there", you'll count 1 space but there are 2 words. Just be sure you update your words variable so your later calculation will be correct. (alternatively, initialize words to 1, since you know you won't ever have zero).

  • Oh I see, by the documentation, 'isspace' takes more space "types" then just 'isblank'. By "update my words variable" you mean I change it to int words = 1 ? Thanks a lot for your help! – pedromndias Jan 28 '20 at 1:56
  • @pedromndias actually, because of that, you should test for a space only. I've edited my answer. – curiouskiwi Jan 28 '20 at 2:59
  • I tried with text[i] == ' ' and worked but for single spaces only. Then I tried putting some extra spaces between the words and it counted as words.. how can I overcome this situation? – pedromndias Jan 28 '20 at 11:18
  • @pedromndias you aren't required to. The spec says that you can assume that all words will be separated by one space only. – curiouskiwi Jan 28 '20 at 18:22
  • thanks for the answer. I am new to this and was suggested to come here for any doubts. My program looks like it is working but failing for grades 2, 7 and 9.. You think it is the sentences? int sentences = 0; for (int i = 0; i < n; i++) { if (text[i] == '!' || text[i] == '?' || text[i] == '.') { sentences++; } } – pedromndias Jan 28 '20 at 18:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .