2

I've attempted to reverse a string using the following code but get a never ending output of small boxes. (1 on each line)

code:

#include <iostream>
#include <math.h>
#include <iomanip>
#include <sstream>



int main() {


     // Reversing A String
    cout<<"welcome to string reverser"<<endl;
    int sizeOfString;
    cout<<"please input size of string"<<endl;
    cin>>sizeOfString;
    char charray3[sizeOfString];
    cin>>charray3;

    for(unsigned int i=sizeOfString-1; i>=0; i--){

    cout<<charray3[i]<<endl;
    }
return 0;
}

in my attempt i set sizeOfString to 3 and set charray3 to 'abc'.

output:

box output

what am i doing wrong?

6
  • 3
    What happens when you step through this code in your debugger? Commented Nov 29, 2016 at 20:01
  • Is sizeOfString supposed to be the number of bytes the string occupies in memory or the number of characters in it? You say you set sizeOfString to 3 for "abc", implying it's the number of valid characters in it, but then you use it as the size of the array to allocate implying it's the memory size. (If you don't understand why it can't be both, you don't understand C-style strings.) Commented Nov 29, 2016 at 20:01
  • 1
    FYI, char charray3[sizeOfString]; is not standard C++ when sizeOfString is not a constant expression. Commented Nov 29, 2016 at 20:02
  • 3
    it's C++, then use std::string, not char array. Commented Nov 29, 2016 at 20:03
  • i know that you can define a string using a char array like so: char array[]="hello";. Passing int to represent the size of the char is valid. Commented Nov 29, 2016 at 20:07

6 Answers 6

5
  1. Standard C++ does not allow you to use a variable as the size of an array.
  2. A string is terminated by a \0 character.
  3. Don't use character arrays but rather std::string.
  4. Your loop will never teminate because i>=0 is always true since i is unsigned (where i will be the bigest value your unsigned can hold after the 0 iteration).
Sign up to request clarification or add additional context in comments.

Comments

5

Don't ask for the size of string. Apart from not being necessary, it makes your program non-standard, because variable-length array construct, char charray3[sizeOfString], is a compiler extension.

Use std::getline instead, it will allocate read as many characters as necessary. After that, print the string in reverse the same way that you did above, or reverse the string in place if you prefer. Be careful with unsigned subtractions! Your compiler should warn you about it, though.

Note: In case you are wondering why your program does not work, there is a leftover '\n' sitting in the buffer after reading an int. Because of that buffered character, the program returns with an empty string as soon as you call cin>>charray3.

Comments

2

You're re-inventing the wheel :) Use std::string and std::reverse:

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string str{"Hello, World!"};
    std::reverse(str.begin(), str.end());
    std::cout << str << std::endl;
}

Here's a working online example.

Comments

0

you can easily use class string:

#include <iostream>
#include <string>


int main()
{

    std::string s1 = "Hello", s2;

    for(int i(s1.length() - 1 ); i >= 0; i--)
        s2+= s1[i];

    std::cout << s1 << std::endl;
    std::cout << s2 << std::endl;

    return 0;
}
  • to solve it in your way using character array the consider:

1- you input the sizeOfString one question: what about the input with cin overflows or underflows the input size (smaller or bigger)???

eg:

sizeOfString = 5;
cin >> charray3; // "ab" now the size is only 3 (+ null terminator)

so writing:

charray3[sizeOfString - 1] = 'c'; // charray3[5 - 1] // charray[4]

while charray4 is not inputted because you inputted only charray3[0] and charray3[1] so as a result a segfault.

to correct it you have to do some extra work:

#include <iostream>
using namespace std;


int main() 
{
     // Reversing A String
    cout << "welcome to string reverser" << endl;
    int sizeOfString;

    cout << "please input size of string" << endl;
    cin >> sizeOfString; // you specified size

    cin.ignore(1, '\n'); // clean the input buffer

    char* charray3 = new char[sizeOfString + 1];
    //cin>>charray3; use getline instead to get whitespaces

    cout << "enter text: " << endl;
    cin.getline(charray3, sizeOfString); // what if the user enter a text smaller or bigger than sizeOfString???
    charray3[sizeOfString] = '\0';
    //to correct it:

    // take effects of input on sizeOfString
    sizeOfString = strlen(charray3);

    cout << "before reversing: " << endl;
    cout << charray3 << endl;
    // to reverse it create a temporary array:

    char* pTmp = new char[sizeOfString + 1];

    for(int i(sizeOfString-1), j = 0; i >= 0; i--, j++)
       pTmp[j] = charray3[i];
    pTmp[sizeOfString] = '\0';

    cout << "after reversing: " << endl;
    cout << pTmp << endl;

    // don't forget to clean:
    delete[] charray3;
    delete[] pTmp;

return 0;
}

1 Comment

i use a forwards loop:unsigned int sizeOfString; cout<<"please input size of string"<<endl; cin>>sizeOfString; char charray3[sizeOfString]; cin>>charray3; for(unsigned int i=0; i<sizeOfString; i++){ cout<<charray3[i]<<endl; } it works perfectly fine.
0
// First method
const int MAXLENGTH = 100;
char s[MAXLENGTH];
cin >> s;
int len = strlen(s);
for(int i = 0; i < len/2; i++) {
    char temp = s[i];
    s[i] = s[len-1-i];
    s[len-1-i] = temp;
}
cout << s;

// Second
string s;
cin >> s;
for(int i = 0, len = s.length(); i < len/2; i++) {
    char t = s[i];
    s[i] = s[len-1-i];
    s[len-1-i] = t;
}
cout << s;

Comments

-2

The code works now mysteriously. 1) I altered the loop to make it a forwards loop and it worked 2) i reverted back to the problem code and removed the unsigned type.

#include <iostream>
#include <math.h>
#include <iomanip>
#include <sstream>



int main() {


 cout<<"welcome to string reverser"<<endl;
    int sizeOfString;
    cout<<"please input size of string"<<endl;
    cin>>sizeOfString;
    char charray3[sizeOfString];
    cin>>charray3;

    for(int i=sizeOfString-1; i>=0; i--){

    cout<<charray3[i]<<endl;
    }
return 0;
}

Thankyou all for your comments and answers. I will try the variety of alternative code presented.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.