Problem with output in C++

Write a program that reads a sentence and then outputs all the words in odd positions each on a seperate line.
For instance, if the input is: A thing of beauty is a joy for ever
The output should be:
A
of
joy
ever

I cannot get the output. Where am I going wrong. Thanks

include

include

using namespace std;

const int NUM = 100;

string removed(string w)
{
int length, i;
length = w.size();
i = length - 1;
if((w[i] == ',') || (w [i] == '.' || w[i] == '?' || w[i] == '!' ))
return w.substr(0,i);
else
return w;
}

int main()
{
string sentence, word;
int start, position, lengthOfWord;
string array[NUM];

cout << "Please enter a sentence: ";
getline(cin, sentence, '\n');

start = 0;
position = sentence.find(" ");

for(int i = 0; i < sentence.size(); i++)
{

lengthOfWord = position - start;
word = sentence.substr(start, lengthOfWord);
array[i] = removed(word);
start = start + lengthOfWord + 1;
position = sentence.find(" ", start);


cout << array[i] << " ";

}

return 0;
}

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories