Word counter | Sololearn: Learn to code for FREE!


Word counter

I just want to count the words with this but it doesn’t work Why??? #include <iostream> using namespace std; int main() { int count=0; cout<<"please enter ur statement"; while(cin.get()!='\n') count++; cout<<count; cin.get(); return 0; }

2/18/2020 8:13:20 PM

Amirhossein Omidi Yekta

1 Answer

New Answer


Try this : int count = 0; string temp; while(cin >> temp) { ++count; } cout << count; This method reads each word (each word must be separated by a space) and returns the total of words. The loop automatically ends when '\n' is read.