1 Replies - 986 Views - Last Post: 01 November 2010 - 12:13 AM Rate Topic: -----

#1 evilcook818  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 22-September 10

I need help with counting words in a string

Posted 31 October 2010 - 11:44 PM

Call a function named countWords that counts the number of words in the current string and displays a message stating how many words are in the string

Examples: The string “2015” has one word
The string “Hello World” has two words
The string “ I am Woman ” has 3 words

This is my program.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
	string str; //declare a string object
	int i;

	cout << "Enter a string:\n";
	getline(cin, str);
	



for (i = 0; i < str.length(); i++)
	int wordcount(char *str){
    int i=0;
    int count=0;
while(&str[i] != "\0"){
    if(&str[i] == "\t"){
        count++;}
   i++;
}
 cout << str << endl;
    return 0;
}


How come its not working.

MOD EDIT: When posting code...USE CODE TAGS!!!

:code:

This post has been edited by JackOfAllTrades: 01 November 2010 - 03:36 AM


Is This A Good Question/Topic? 0
  • +

Replies To: I need help with counting words in a string

#2 oscode  Icon User is offline

  • D.I.C Regular

Reputation: 109
  • View blog
  • Posts: 257
  • Joined: 24-October 10

Re: I need help with counting words in a string

Posted 01 November 2010 - 12:13 AM

You are defining a function within another function, this is not allowed. You aren't calling the function you have defined. You might want to look at <ctype>'s isspace function and how to access elements of character arrays, you don't want to take the address of a character in an array to check its value.

If efficiency isn't a problem, you can use the fact that reading a string from a stringstream takes a word and no whitespace to your advantage.

string input, word;
if(getline(cin, input))
{
    stringstream ss(input);
    for(int wordCount = 0; ss >> word; wordCount++)
        ;
}



Your teacher will see this isn't your code, you should research it or continue on your attempt with the advice i gave above.

This post has been edited by oscode: 01 November 2010 - 12:14 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1