Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over the words of a sentence in C++?

Tags:

c++

string

loops

My input is "Hello World" and my targeted output is "olleH dlroW".

So my idea is to get the sentence into a variable and then loop over the words in the sentence, reverse each of them and finally concatenate them into a new variable.

My question is: how to iterate over the words of the sentence?

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

string reverseword(string word)
{
    string rword;
    int size = word.length();
    while (size >= 0)
    {
        rword+= word[size];
        size = size -1;
    }   
    return rword;
}

int main()
{ 
    string sentence;
    cout<<"Enter the word/sentence to be reversed: ";
    cin >> sentence;
    string rsentence;
    // for every word in the sentence do
    {
        rword = reverseword(word);
        rsentence = rsentence + " " + rword; 
    }
    cout<<rword;
    return 0;
}
like image 215
astudentofmaths Avatar asked Mar 08 '23 19:03

astudentofmaths


1 Answers

Before you can iterate over words in a sentence, you need to read a sentence from input. This line

cin >> sentence;

reads the first word of a sentence, not the whole sentence. Use getline instead:

std::getline(std::cin, sentence);

With sentence in memory, you can iterate it word-by-word using istream_iterator as follows:

stringstream ss(sentence);
for (auto w = istream_iterator<string>(ss) ; w != istream_iterator<string>() ; w++) {
    string &word = *w;
    ...
}

Demo.

like image 92
Sergey Kalinichenko Avatar answered Mar 11 '23 00:03

Sergey Kalinichenko