0


So main line is 8 Code is given below and program is about reversing the string. Basically I have given the character value 80 I want help so If I enter value it will reverse the string

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
void reverse(char[], int);
int main()
{
    char a[80];
    int length;
    cout << "\n Enter text:";
    cin >> a;
    length = strlen(a);
    cout << "\n The orginal string is:";
    puts(a);
    reverse(a, length);
    cout << "\n The modified string is:";
    puts(a);
}
void reverse(char str[], int l)
{
    char temp;
    for (int i = 0; i < l / 2; i++) {
        temp = str[i];
        str[i] = str[l - i - 1];
        str[l - i - 1] = temp;
    }
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 2
    `char a[];` is invalid. Whatever C++ books you're using they don't teach you C++, but rather C (and barely that). C++ have a `std::string` class for all dynamic string uses. [Here's a list of good books](https://stackoverflow.com/a/388282/440558), I really recommend you invest in a couple of the beginners books. – Some programmer dude Aug 29 '21 at 14:58
  • You should use `string`, not `char[]`. It's C++ after all. – ypnos Aug 29 '21 at 14:59
  • I corrected the code I want to change char[80] . So if I enter any value it will show me the reverse of it – Shubham Singh Aug 29 '21 at 15:03
  • Note that `cin >> a;` will read up to the first space typed. Your code appears to work if you type a string that does not include any spaces and is less than 79 characters in length (so it allows for the null terminator): [https://ideone.com/XAL9n9](https://ideone.com/XAL9n9) – drescherjm Aug 29 '21 at 15:04
  • Thank you. I solved my problem with help of @drescherjm Thanks for helping a beginner in C++ – Shubham Singh Aug 29 '21 at 15:14
  • 1
    If you are exploring arrays this is fine :) In full C++ mode I would write #include #include std::string str{"Hello world!"}; std::reverse(str.begin(),str.end()); and str would be reversed. It is like @Someprogrammerdude says, most C++ courses teach "C" approaches not "C++" – Pepijn Kramer Aug 29 '21 at 15:30

0 Answers0