counting words in string and printing out longest word

Nov 7, 2013 at 2:12pm
In this task you can enter whatever sentence, words separated only with spaces, thats the task given to me, and then program counts how many words ar there in a sentence and then should find longest word. Basicly im done so far as for counting the words, dont want enyone to tell me the code, but just give advice, in which direction to look, to find the longest word. I shoud somehow get function to check each word.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
#include<cstring>
using namespace std;
int main()

{
    string teikums;
    int vardi, garums;
    cout<<"Write a sentence\n";
    getline (cin,teikums);
    
    garums=teikums.length();
    vardi=1;
    
    for (int i=0; i<garums; i++) 
       {
        if (teikums[i]==' ') vardi++; 
        }
        cout<<"Word count in sentence: "<<vardi<<endl; 
   
   
    
    cin.get();
    return 0;
}
Nov 7, 2013 at 2:16pm
I believe I should use find function to find position of spaces, but somehow im stuck to create the cycle, so the function would continue to look for tem and besides after the last word there is no space.
 
int position=teikums.find(" ");
Topic archived. No new replies allowed.