just curious why this isnt working... its probably simple..

but its a friday so im allowed to not access my brain as much...

anyways... i want to input a string then switch that to a char array
then switch back and print reversed string

this doesnt work...
debugger stops it at output.at(x).... but doesnt tell me why.

#include <iostream>
#include <cstring>
using namespace std;

int main () {
    
    string input;
    string output;
    char bob[20];

    int y = 0;
    int x = 0;
    cin >> input;
    cout << endl;
    
    int length = input.length();
    cout << length;


for (y = 0; y < length; y++)
          bob[y] = input.at(y);
          

for (y = (length -1 ); y >= 0; y--) {
    
             output.at(x) = bob[y];
             x--;
             
               

}

cout << output;


return 0;
}

>#include <cstring>
This doesn't give you the string class, it gives you the C-style string functions. Why not reverse the string in place?

int i = 0;
int j = input.size() - 1;

while ( i < j )
  std::swap ( input[i++], input[j--] );

>#include <cstring>
This doesn't give you the string class, it gives you the C-style string functions. Why not reverse the string in place?

because im putting this into a stack that reads in a string... then goes through the characters and outputs it as a reversed string.

Okay, then in that case your output string is empty, so indexing it will surely be out of bounds. You also count x down when it should be going up:

#include <iostream>
#include <string>
using namespace std;

int main () {
  string input;
  string output;
  char bob[20];

  int y = 0;
  int x = 0;
  cin >> input;
  cout << endl;

  int length = input.length();
  cout << length;

  for (y = 0; y < length; y++)
    bob[y] = input.at(y);

  output.resize(length);

  for (y = (length -1 ); y >= 0; y--) {
    output.at(x) = bob[y];
    x++;
  }

  cout << output << endl;

  return 0;
}

Thank you narue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.