Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • String Reverse Weird Behavior - C++
    #include <stdio.h>
    void StrRev(char str[]) {
        int len=strlen(str);
        char out[len];
        int i;
        for(i=0;i<len;i++){
            out[i]=str[len-i-1];
        }
        printf("%s",out);
    }
    int main(void) {
      StrRev("TestString");
      return 0;
    }
    
    This should run OK, but there's garbage characters at the end for certain strings. What's happening?
    RicardoLuis0 posted this question on 7/15/16 | first, reverse, cpp
    Answers
  • +
  • 1
  • -
  • The STR cout in main is not showing any string in input for the question first reverse
    #include <iostream>
    #include <string>
    using namespace std;
    
    string FirstReverse(string str)
    {
    	int l=str.length();
    	for(int i=0;i<(int)l/2;i++)
    	{
    		string temp="";
    		temp=str[i];
    		str[i] = str[l-i-1];
    		str[l-i-1] = temp[0];
    	}
    	return str;
    }
    
    int main() 
    {
    	string str;
    	getline(cin,str);
    	cout << "STR=" << str;
    	cout << FirstReverse(str);
    	return 0;
    }
  • +
  • 0
  • -
  • You need a '\0' at the end, also your version won't compile on G++. Try it like this:
    
    #include <stdio.h>
    void StrRev(char str[]) {
    	int len = strlen(str);
    	char *out = new char[len];
    	out[len] = '\0';
    	int i;
    	for (i = 0; i<len; i++) {
    		out[i] = str[len - i - 1];
    	}
    	printf("%s", out);
    }
    
    But this is C code, not C++. This is C++:
    #include <string>
    std::string StrRev2(std::string str) {
    	int len = str.length();
    	int middle = len & 1 ? len / 2 - 1 : len / 2;
    	for (int i = 0; i < middle; i++) {
    		char temp = str[i];
    		str[i] = str[len - i - 1];
    		str[len - i - 1] = temp;
    	}
    	return str;
    }
    
  • +
  • 0
  • -
  • You miss the last '\0' of the string out And the total length of it should be len+1
  • +
  • 0
  • -
  • To display code include the following tags:
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
     
    void main()
    {
        clrscr();
        char str[50];
        char *reversed;
        printf("Enter any string to be reversed: ");
        scanf("%s",str);
     
        /*this function may not be work in some compilers*/
        reversed = strrev(str);
     
        printf("Reverse string is : %s",reversed);
        getch();
    }
    Log in to write an answer.