I need some help debugging my code. This code is intended to reverse the words in a string that is in the form of a sentence [assuming that the string does not have a "." at the end]. For some reason what I'm getting as an output is the indented output plus an extra space after the first word as well as the indented output minus the first word. I am a beginner at coding; so if possible, I would appreciate more simple to understand solutions, or a solution that uses a loop, strings, and arrays. Also, there is also an extra space at the end. If there is a way to maybe cancel outputting the last space; please tell me.
#include <iostream>
#include <string>
//#include <stdio.h>
#include <cctype> // for std::issspace
// using namespace std;
int main() {
std::string s, n ; //, a; // consider using semantically richer names for these
std::getline( std::cin, s );
std::cout << '"' ; // print an opening quote
//for( int i = s.length(); i >= 0; i-- ) {
for( int i = s.length() - 1; i >= 0; i-- ) { // start from length - 1
//if( s[i] != 32 ) {
if( !std::isspace(s[i]) ) { // the value of the space character need not be 32
n += s[i];
}
else {
// print out the word (the contents of n in reverse)
for( int j = n.length() - 1; j >= 0; j-- ) {
// a += n[j];
std::cout << n[j] ;
}
// std::cout << a << ' ';
std::cout << ' ' ; // and then a space
n.clear();
//a.clear();
}
}
// print the last word - the residual characters
// that may be remaining in n (in reverse)
for( int i = n.length() - 1 ; i >= 0 ; --i ) std::cout << n[i] ;
std::cout << "\"\n" ; // print a closing quote and a new line
//cin.ignore();
//getchar();
//return 0;
std::cout << "\npress enter to exit program: " ;
std::cin.get() ; // wait for the user to hit enter
}
Thank you for helping me refine and debug my code, I realized my problem with the extra space as well as that I needed a space to read the first word in the string.