I am preparing for an entry-level job interview. I am trying to reverse the order of words in a string, but my output is a bunch of junk that makes no sense. I think the problem may be because I'm using "char*" for my functions? Anyways, heres my code
#include <iostream>
#include <string>
using namespace std;
char* reverse(char* str, int a, int b);
char* reversewords(char* str);
int main()
{
char str[] = "The interview is";
cout<<"Reverse is: "<<reversewords(str);
cin.ignore();
return 0;
}
char* reverse(char* str, int a, int b)
{
int length = a-b;
for (int i=a; i<b+1; i++)
{
char c =str[length-i-1];
str[length-i-1]=str[i];
str[i] = c;
}
return str;
}
char* reversewords(char* str)
{
int length = strlen(str);
int a=0;
int b=0;
while (b<length)
{
if (str[b]==' ' || b==length-1)
{
b=b-1;
reverse(str, a, b);
a=b+2;
b=a;
}
b++;
}
return str;
}