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