Help with strings

Hi there!
I´ve been trying to solve a simple problem that consists in making a code that asks the user to type a phrase, after that it prints the same phrase and a second one (associated with a second string) that is basically the first one reversed.
The code i wrote keeps associating strange values to j, and/or crasing when i use the scanf_s function insteado of the gets_s one.
Also logically, at least for me, it seems correct. Please tell me if i missed something.

Thanks, Onpocket


Here's the [code]

#include <stdio.h>
#include <string.h>
#define TAM 1000
void main()
{
char frase1[TAM], frase2[TAM];
int i = 0, j = 0;
printf("Type a phrase:");
scanf_s("%999s", frase1); /*I've already tried gets_s instead of scanf_s (it scans the phrase but then doesnt write frase2)*/
while (frase1[TAM] != '\0')
i++;
for (i; i >= 0; i--) /*I've also tried to put j++ next to i-- (i-- && j++)*/
{
frase2[j] = frase1[i];
j++;
}
printf("Old phrase: %999s\n", frase1);
printf("New phrase: %999s\n", frase2);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <string.h>
#define TAM 1000
int main()
{
    char frase1[TAM], frase2[TAM];
    int i = 0, j = 0;
    printf("Type a phrase: ");
    scanf_s("%999s", frase1);
    while (frase1[i] != '\0') i++; // "[i]" instead of "[TAM]"
                                   // you could just say i = strlen(frase1);
    for (; i > 0; i--) {           // deleted "i" to avoid warning
        /**
             indexing starts from 0; so if len of frase1 is 4, then
                 frase2[0] = frase1[3]
                 frase2[3] = frase1[0]
        **/
        frase2[j] = frase1[i - 1];
        j++;
    }
    frase2[j] = '\0';              // you need to add null char manually
                                   // 't' 'e' 's' 't' '\0'  -> 't' 's' 'e' 't' '\0'
    printf("Old phrase: %999s\n", frase1);
    printf("New phrase: %999s\n", frase2);
    return 0;
}
Topic archived. No new replies allowed.