0

Output showing me only the first letter of string

//program to reverse all words except corner words
#include <bits/stdc++.h>
using namespace std;

void printReverse(string str)
{
    //print first word
    int i = 0;
    for (i = 0; i < str.length() && str[i] != ' '; i++)
        cout << str[i];
    //print middle word
    string word = "";
    for (i = 0; i < str.length(); i++)
    {
        if (str[i] != ' ')
            word += str[i];
        else
        {
            reverse(word.begin(), word.end());
            cout << word << " ";
            word = "";
        }
    }
    //print last word
    cout << word << " ";
}

int main()
{
    string str;
    cout << "Enter the string: ";
    cin >> str;
    printReverse(str);
    return 0;
}

Program to reverse all words except corner words. I'm not able to recognize what's wrong. It showed me only the first word of the string and the rest part of the code is working. Please help me.

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • 3
    cin >> str reads a single token from output. For a series of words, you should use std::getline(cin, str); – utnapistim Aug 20 '20 at 08:53
  • Also to avoid printing the first word twice you should store its lenght and start the second for loop from that index, otherwise with input Test1 Test2 Test3 Test4 Test5 You get output Test11tseT 2tseT 3tseT 4tseT Test5 – User.cpp Aug 20 '20 at 08:58
  • 2
    also [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and never use [#include ](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – yaodav Aug 20 '20 at 09:01
  • I would just [split the string](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) into the vector of strings and print it in the following order: `words[0]`, `words[last-1] ... words[0]`, [words[last]`. If I understood correctly "corner words". – pptaszni Aug 20 '20 at 12:30
  • Please add some examples of inputs, outputs, and expected outputs. – cigien Aug 20 '20 at 13:43

1 Answers1

0
public class HelloWorld {
public static void main(String[] args) {

    String str = "Reverse string except corner";
    int left = 0, right = 0;
    int i = 0;  
    for(i = 0; i < str.length() && str.charAt(i) != ' '; i++)
    {
      System.out.print(str.charAt(i)); // Printing the first word
    }
    
    left = i;        
    String last = " ";
    
    for(int j = str.length()-1; j >=0 && str.charAt(j) != ' '; j--)
    {
      last = str.charAt(j) + last; // Storing the last word 
      right = j;
    }
    
    String mid = str.substring(left, right); // Getting the middle words

    for(int k = mid.length()-1; k >= 0; k--)
    {
      System.out.print(mid.charAt(k));  
    }
    
    System.out.println(last);        
 }
}

Output

ouflak
  • 2,458
  • 10
  • 44
  • 49