Thread: words count

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    3

    words count

    hello everyone.

    here is my own first algorithm. it only counts the number of words in a line.
    from my testings it works just fine.

    let me know what you think and if there is a better way to write it.

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(){
    
    	int wordCount = 0;	
    	
    	string words;
    	getline(cin, words);
    	int length = words.length();
    	
    	for(int index = 0; index <= length; ++index){
    		
    			while(words[index] != 32){
    				++index;
    			}
    			++wordCount;
    			while(words[index] == 32){
    				++index;
    			}
    		
    }
    	if(words[0] == 32)
    		--wordCount;
    
    	cout << wordCount << endl;
    		
    		return 0;
    		
    }

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Couple of suggestions
    - trim all white space from the beggining and end of the string (put multiple white space at the beginning and end of the input and see if your code is still correct)
    - don't use magic numbers, use this instead
    Code:
    const char SPACE = ' ';
    - and finally, there may be something similar to strtok() in STL that you can use to tokenize the string based on spaces (one of you STL gurus will have to help on that).

    gg

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    28
    Greetings,

    I'm no guru but this should do it:
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
        int wordCount = 0;
        std::string words;
        std::getline(std::cin, words);
        std::istringstream is(words);
        while (is >> words)
    	wordCount++;
        std::cout << wordCount << std::endl;
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help, i cant count spaces or words
    By cdosrun in forum C Programming
    Replies: 2
    Last Post: 11-25-2005, 03:13 PM
  2. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM
  3. New Theme
    By XSquared in forum A Brief History of Cprogramming.com
    Replies: 160
    Last Post: 04-01-2004, 08:00 PM
  4. Replies: 2
    Last Post: 05-05-2002, 01:38 PM