0

I am trying to solve this problem.

Write a program that reads one line of text(less than 50 words) and then prints it with each word reversed. For example:

Input: Today is Tuesday
Output: Tuesday is today

And all I'd think of is putting the words in the sentence into an array, and then printing them out from the biggest index to the smallest index. So I write this program, but it won't work. Please help me fix it, thanks so much.

I tried to let it print the words with the index number and I found out that the last "box" of the array stored the whole sentence. But I don't know what's wrong. I don't know where(which line of code) it stored that sentence.

#include <bits/stdc++.h>
using namespace std;

int main(){
    string str;
    cout<<"Put in your sentence: ";
    getline(cin,str);
    string strWords[10];
    int counter = 0;
    for (int i = 0; i<str.length(); i++){
    if (str[i] == ' ')
        counter++;
    else
        strWords[counter] += str[i];
    }

    int j=9;
    do{
        cout<<j<<": "<<strWords[j]<<" ";
        j--;
    }
    while(j>=0);

    return 0;
}

example:

input:

Put in your sentence: WE are the people.

output:

9: WE are the people. 8:  7:  6:  5:  4:  3: people. 2: the 1: are 0: WE
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
JulIa0621
  • 1
  • 1
  • 4
    Couple of problems immediately 1) The question says up to 50, your code assumes exactly 10. 2) Your code does not deal correctly with multiple spaces between a word. You could solve the first problem quite easily by using a vector instead of an array. – john Aug 21 '23 at 08:24
  • 4
    [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Biffen Aug 21 '23 at 08:25
  • 1
    [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – 463035818_is_not_an_ai Aug 21 '23 at 08:30
  • 2
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – 463035818_is_not_an_ai Aug 21 '23 at 08:30
  • You could browse through the standard library to find things that can help. [Example](https://godbolt.org/z/9snzWbd89) – Ted Lyngmo Aug 21 '23 at 08:30
  • How would I do that with a vector? – JulIa0621 Aug 21 '23 at 08:31
  • @JulIa0621 _"How would I do that with a vector?"_ - See my Example above. – Ted Lyngmo Aug 21 '23 at 08:32
  • I can't reproduce the error you are asking about. Your code splits a sentence into it's words for me. (As long as there are no leading spaces, and the words are separated by single spaces). – john Aug 21 '23 at 08:35
  • 1
    please include example input, output, and expected output in the question. "I found out that the last "box" of the array stored the whole sentence" its not clear what that means. It is much simpler if you show us the issue rather than only describing it – 463035818_is_not_an_ai Aug 21 '23 at 08:41
  • there, input and output – JulIa0621 Aug 21 '23 at 08:47
  • @JulIa0621 Your shown code works [as you can see here](https://godbolt.org/z/3ab6sG37c). – Fareanor Aug 21 '23 at 08:47
  • OK,I will quickly learn vector and check that out. – JulIa0621 Aug 21 '23 at 08:48
  • WHATTTT! WHY DOES MY CODE WORKS FOR EVERYONE BESIDES ME!!!! – JulIa0621 Aug 21 '23 at 08:49
  • @john ok then, thanks anyway – JulIa0621 Aug 21 '23 at 08:50
  • @JulIa0621 If you would consider using the standard library, you could use a `std::vector` instead (it would make your code more flexible with arbitrary sized inputs). Then `std::istreamstring` could do the space parsing for you. Something [like that](https://godbolt.org/z/MdnGsqG6d). – Fareanor Aug 21 '23 at 08:54
  • @Fareanor Ok, thanks, I'll try that. – JulIa0621 Aug 21 '23 at 08:56
  • You don't need arrays or anything fancy for this - the simplest way to do this is (1) reverse the whole string (in place), then (2) reverse each word (in place). – Paul R Aug 21 '23 at 09:40
  • @JulIa0621 There could be lots of reasons for that. I guess the most likely is that you are not running the code you think you are running (like you forgot to save the file before you compiled the code, or something along those lines). You probably need to do a sanity check. – john Aug 21 '23 at 10:10
  • [std::reverse](https://en.cppreference.com/w/cpp/algorithm/reverse) exist and could be part of a solution. – Jesper Juhl Aug 21 '23 at 10:18
  • [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Jesper Juhl Aug 21 '23 at 10:21
  • 1
    Another way to do this is to use `std::istringstream` and `std::stack`. Do you know what a `std::stack` is? It is a last-in, first-out data structure. You put each word found into the stack, and when done, you just pop each word out of the stack, where each word popped out is added to a string that starts out empty. – PaulMcKenzie Aug 21 '23 at 12:09
  • 1
    [Using std::istringstream and std::stack](https://godbolt.org/z/a6Tj8bY4q). – PaulMcKenzie Aug 21 '23 at 12:16
  • The problem statement does not require reversing the order of the words in storage. It only requires that they be reversed when printed. So I like idea of pushing them onto a stack and then popping them off to print them. – tbxfreeware Aug 21 '23 at 12:26
  • Here is a [solution](https://godbolt.org/z/hYshE84jx) that uses a simple `vector`. Function `push_back` adds the strings at the end of the vector, and a looping idiom allows you to scan the vector in reverse order. Here are four things you could study to help you understand why this solution works: 1. `std::vector::push_back`, 2. `std::stringstream`, 3. This idiom for accessing the elements of a vector in reverse order: `for (auto i = v.size(); i--;) ...`. and 4. This idiom for looping until stream input fails: `while (sst >> s) ...`. Hope this helps! – tbxfreeware Aug 21 '23 at 12:58
  • You've found a trick question/problem. There is a normal solution which is inefficient, tedious and boring, and a trick solution which is efficient, short and brilliant. Try to find the tricky solution. Hint: you only need storage for the sentence, not for individual words. All reversal is done in place. – n. m. could be an AI Aug 21 '23 at 14:41

1 Answers1

1

I can not reproduce the problem. However in any case this for loop

int counter = 0;
for (int i = 0; i<str.length(); i++){
if (str[i] == ' ')
    counter++;
else
    strWords[counter] += str[i];
}

is wrong because the user can enter adjacent spaces that can result in using an incorrect index to access the array strwords. And you should preserve the number of spaces between words when the sentence will be outputted.

Just to output a sentence with its words in the reversed order neither array or other container is required. And there is no need to change the original sentence.

You can use for example standard class std::string_view.

Here is a demonstration program.

#include <iostream>
#include <string>
#include <string_view>

int main()
{
    std::string s;

    std::cout << "Put in your sentence: ";

    if ( std::getline( std::cin, s ) && !s.empty() )
    {
        const char *blank = " \t";

        bool skip_blanks = true;

        std::cout << '\"';

        for (std::string_view sv( s ); sv.length() != 0; )
        {
            auto pos = skip_blanks 
                ? sv.find_last_not_of( blank )
                : sv.find_last_of( blank );

            skip_blanks = !skip_blanks;

            pos = pos == std::string_view::npos ? 0 : pos + 1;

            std::cout << sv.substr( pos );

            sv.remove_suffix( sv.length() - pos );
        }

        std::cout << "\"\n";
    }
}

Its output might look like

Put in your sentence: 1 2 3 4 5 6 7 8 9 10
"10 9 8 7 6 5 4 3 2 1"

If actually you want to change the source sentence by reversing its words then you can use standard algorithm std::reverse.

Here is a demonstration program.

#include <iostream>
#include <iomanip>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string s;

    std::cout << "Put in your sentence: ";

    if (std::getline( std::cin, s ) && !s.empty())
    {
        const char *blank = " \t";

        for (std::string::size_type last = 0, first = s.find_first_not_of( blank, last );
            first != std::string::npos;
            first = s.find_first_not_of( blank, last ))
        {
            last = s.find_first_of( blank, first );
            if (last == std::string::npos) last = s.size();
            std::reverse( std::next( std::begin( s ), first ), std::next( std::begin( s ), last ) );
        }

        std::reverse( std::begin( s ), std::end( s ) );

        std::cout << std::quoted( s ) << '\n';
    }

Its output might look the same way as shown above for the preceding demonstration program.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335