Hi guys, I think this is my first post here. I am looking for a solution to a problem to a programming problem that I've spent ages on, but can't seem to fix. I've searched for other threads, but none are using the same code as me and they seem to be complicated.
Okay, so I am a beginner to programming and am using this problem as an exercise. I am basically trying to print out text input by the user, but in reverse. Here is the code:
I am using TextMate and compiling using gcc in the Terminal. Whenever I enter the string, it just prints out garbled nonsense of the same length. I've introduced a null variable, which is equal to the length of the string plus 1, so the for loop knows when to stop. Before I used that, I used the r variable for that, then I spotted my mistake. Problem is, the output hasn't changed much, still just junk.
Bizarrely, when I change the text and reverse character amount from 50 to 51, it just outputs a blank line. This is really confusing, please help.
Here's a screenshot of me compiling and running the app, once with the 51 chars in the arrays, the second time with 50.
Okay, so I am a beginner to programming and am using this problem as an exercise. I am basically trying to print out text input by the user, but in reverse. Here is the code:
Code:
#include <stdio.h>
#include <string.h>
int main ()
{
char text[50];
char reverse[50];
int t;
int r;
int null;
printf("Enter some text (max 49 characters): ");
scanf("%s", text);
r = strlen(text) - 1;
null = r + 1;
for (t = 0 ; t <= null ; t = t + 1, r = r - 1)
{
text[t] = reverse[r];
}
printf("%s\n", reverse);
fflush(stdin);
getchar();
}
I am using TextMate and compiling using gcc in the Terminal. Whenever I enter the string, it just prints out garbled nonsense of the same length. I've introduced a null variable, which is equal to the length of the string plus 1, so the for loop knows when to stop. Before I used that, I used the r variable for that, then I spotted my mistake. Problem is, the output hasn't changed much, still just junk.
Bizarrely, when I change the text and reverse character amount from 50 to 51, it just outputs a blank line. This is really confusing, please help.
Here's a screenshot of me compiling and running the app, once with the 51 chars in the arrays, the second time with 50.
Attachments
Last edited: