Recognize the 'enter' key in C

I am trying to make a code that prints only the third stop of a typed string, but my program is endless, how to recognize the given enter so that the program ends?

#include <stdio.h>
#include <stdlib.h>

int main()
{
char **texto= NULL;
int i=0,j;
char letra;

do{
    texto=(char**) realloc(texto, (i+1)*sizeof(char*));
        do{ texto[i]= NULL;
            j=0;
            letra=getchar();
            texto[i]=(char*)realloc(texto[i], (j+1)*sizeof(char));
            texto[i][j]=letra;
            if ((i+1)%3==0){
                printf("%c", letra);
            }
            j++;
        }while(letra!=' ');
        i++;
        printf("%d", (int)letra);
}while ((int)letra!=10);

free(texto);

return 0;
}
Author: Maniero, 2020-06-30

2 answers

Are you sure you need all this complication and inefficiency? Is that a requirement? The most correct way to do this is not so. Much of what this code does is even useless. Never use code like this in a real situation.

To solve the problem you have to analyze if you entered a line break that varies according to the operating system so you can not use a fixed code, you have to adopt the generic character that indicates line break, so the compiler puts the correct code.

Actually the code has several errors. One of them is that you have to analyze if you have typed the end of line in the inner loop as well.

Had variable initializations in the wrong place.

I made other improvements.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char **texto = NULL;
    int i = 0;
    char letra;
    do {
        texto = realloc(texto, (i + 1) * sizeof(char*));
        texto[i] = NULL;
        int j = 0;
        do {
            letra = getchar();
            texto[i] = realloc(texto[i], j + 1);
            texto[i][j] = letra;
            if (i == 2) printf("%c", letra);
            j++;
        } while (letra != ' ' && letra != '\n');
        i++;
    } while (letra != '\n');
    free(texto);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 1
Author: Maniero, 2020-07-02 12:54:25

Why don't you do it like this:

while ( scanf("%...",&...) != EOF )
{
    ......
    ......
    ......
}
 0
Author: RUBEM ALVES FIGUEREDO, 2020-12-02 01:48:10