My program is to read a string from user and reverse it. When I use gets in Visual studio and Dev C++ gives me the right output but Linux gives me a warning and doesn't take it. When I use fgets instead of gets in all of them, the IDE's print out the reverse strings in new lines instead of printing all the words in the same line. Length is also different between gets and fgets.
#include <stdio.h>
#include <string.h>
void reverse(char *str, int i, int j); //function prototype
int main()
{
char str[100];
int start = 0;
int i = 0, len;
printf("Enter a string: \n");//fire work
gets(str);//fgets(str,100,stdin) //strtok(str,"\n")->outouts garbage
len = strlen(str);
printf("length %d\n",len);
while (i < len) //we find the position of all the words and reverse them using the function
{
printf("i=%d\n", i);
if (*(str + i) == ' ')
{
reverse(str, start, i - 1);
while (i < len && *(str + i) == ' ')
i++;
start = i;
}
i++;
}
reverse(str, start, len - 1);
printf("%s\n",str); //printing the reversed string
return 0;
}
void reverse(char *str, int i, int j) //function to reverse str string in
str given range
{
char ch;
if (i >= j)
return;
ch = *(str + i);
*(str + i) = *(str + j);
*(str + j) = ch;
reverse(str, ++i, --j);
}
//edit
My expected output should be
length is 9.
erif krow
end of edit//
gets(str) gives -
Visual Studio and Dev C++:
length is 9.
erif krow.
MobaXterm(Linux)
warning for gets
fgets(str,100,stdin) gives for all IDEs -
length is 10.
erif
krow