does anyone know how to make an array search for how many words are in it?

Dani AI

Generated

's original problem comes from reading only the first token with cin >> Phrase; — as noted, operator>> stops at whitespace. and gave the sensible quick fix (read the full line and split on whitespace), but a few practical points are missing: counting spaces is fragile (multiple spaces, tabs, punctuation), and strtok is a C-style approach that mutates buffers and is less safe with std::string (as suggested).

A robust approach is to treat a "word" as a contiguous run of letters/digits (optionally allowing internal apostrophes or hyphens for contractions). The example below uses std::regex to find tokens that look like words:

#include <string>
#include <regex>
#include <iterator>

int countWords(const std::string &s) {
  static const std::regex re(R"([A-Za-z0-9]+(?:['-][A-Za-z0-9]+)*)");
  return std::distance(std::sregex_iterator(s.begin(), s.end(), re),
                       std::sregex_iterator());
}

If avoiding regex is preferred (lighter weight and deterministic), a simple state-machine scan is reliable and fast — mark entry to a word on the first alnum and count transitions, remembering to cast chars to unsigned char before calling std::isalnum to avoid UB with negative char values:

#include <string>
#include <cctype>

int countWordsManual(const std::string &s) {
  bool inWord = false;
  int count = 0;
  for (unsigned char ch : s) {
    if (std::isalnum(ch)) {
      if (!inWord) { inWord = true; ++count; }
    } else {
      inWord = false;
    }
  }
  return count;
}

Notes: decide a policy for contractions/hyphenation up front (regex above treats "don't" and "well-known" as single words). For true Unicode-aware tokenization (non-ASCII letters) use a Unicode library (ICU) rather than std::isalnum. For the original 80-character input constraint, read the full line (e.g. std::getline) then enforce the length before counting.

Recommended Answers

All 9 Replies

Can you give an example of what you mean ?

if you ask the user to enter a phrase of no more that 80 characters.

I love programming!

how do you write the part that will search and display the number of words in the phrase. In this case it would be three.

does anyone know how to make an array search for how many words are in it?

Yes... I do.

See the end of your last thread.

I was thinking about using the .length() but i think that will only count the first word. this is what i have so far.

//Get the user to enter a sentence
	cout<<" Please enter a sentence.\n";
	cin>> Phrase;
	cout<<" The number of words in your phrase is "<<Phrase.length()<<".\n";

Have you debugged your code. You are getting only first word by cin>> Phrase; statement.
Why this is happening? Oh Cin delimits the string by SPACE . Ok, so
You need to get whole line first. Than search all space and count all words i.e. no of space + 1

use getline() and istringstream and your problem should be solved.

use getline() and istringstream and your problem should be solved.

look as far as u have a problem of counting words in your phrase then a solution to your problem is "just count the number spaces in your phrase and add 1 in it". for example in phrase "I Love Programming" there are 2 space characters. 1 after I and 2nd after Love + 1 for last word. so u will get answer 3.

1 more very good solution is use "strtok" and tokenize your phrase on space character. then just count the number of tokens.

i think second solution is better than the first one.

Check out this snippet you have:

//Get the user to enter a sentence
	cout<<" Please enter a sentence.\n";
	cin>> Phrase;
            cout<<" The number of words in your phrase is "
          <<Phrase.length()<<".\n";

If you are ONLY looking for words, not the entire string length, then Phrase.length() won't work because it includes spaces. Pseudocode:
1) User enters string
2) Look for letters only which indicates program is in the middle of a word
3) If space is encountered, ignore it and consider one word in the string to be counted.
4) repeat until end of string

>>1 more very good solution is use "strtok"
Not quite.

using the stringstream is safer :

string sentence = string("hello this is a sentence");
stringstream phraser;
phraser << sentence;
int wordCount = 0;
string temp;
while(phraser >> temp){
   ++wordCount;
}
cout << "There are " << wordCount << " words in this sentence :' "<<sentence << " ' \n";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.