How to get a sentence?

closed account (oLC9216C)
I want to get a sentence. also check how many words in the sentence.

I tried to use string like this

1
2
string line;
cin >> line;


For example I enter "how are you"
But the value of line is only "how"

How can I get the whole sentence?
Also how can I check the third word in the sting?
If there is one sentence per line, you can use:
1
2
string line;
getline(cin, line);


If you are reading from a file and there may be multiple sentences per line, you can delimit with a period:
1
2
string line;
getline(cin, line, '.');
Last edited on
to get a whole line instead of cin >> line; which only gets the first word use this
getline(cin, line); this gets the whole line =p
and as far as a word count you can do something like this:
1
2
3
unsigned int num = 1;
for(unsigned int i = 0; i<str.size(); i++) if(str[i] == ' ') num++;
    cout << "Word count is: " << num << endl;
closed account (oLC9216C)
Is it possible to read what is the first three element in the string?
You mean only read in the first three words?
you would have to modify the other code I gave you so that after num reaches 3 it stops reading it but im pretty tired so gl.
Topic archived. No new replies allowed.