The following code is suppose to grab the first word of a sentence (if there's one) and print it letter by letter (The printing part works). The problem that I've encountered is that whenever I input a sentence in the prompt, it grabs every word in the sentence and not the first word (cin is suppose to stop at the first space,enter, etc... so I think the part that is wrong here is the while loop). How can I fix the issue? I think there's something I'm not understanding.
#include <iostream>
using namespace std;
int main(void){
int i = 0;
int length= 25;
string word[length];
cout << "Type another word: (Press Ctrl + D to quit):";
while( i < length && cin >> word[i]){
i++;
cout << "Type another word: (Press Ctrl + D to quit):";
}
for(int j = 0; j < i; j++){
cout<< endl << word[j]<< endl;
for(int k = 0; k < word[j].length(); k++)
cout << word[j].at(k) << endl;
}
}
As we can see this grabs the entire sentence and because of this it prints another prompt not needed.
EXAMPLE OF OUTPUT:
Type another word: (Press Ctrl + D to quit):testing this
Type another word: (Press Ctrl + D to quit):Type another word: (Press Ctrl + D to quit):december
Type another word: (Press Ctrl + D to quit):
testing
t
e
s
t
i
n
g
this
t
h
i
s
december
d
e
c
e
m
b
e
r
I will attach an 'ideal' output:
Type another word: (Press Ctrl + D to quit):testing this
Type another word: (Press Ctrl + D to quit):december
Type another word: (Press Ctrl + D to quit):
testing
t
e
s
t
i
n
g
december
d
e
c
e
m
b
e
r