Recognize enter key in C

Asked

Viewed 1,848 times

1

I’m trying to make a code that only prints the third to a typed string, but my program is endless, how to recognize the given enter for the program to end?

#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;
}

2 answers

1


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

To solve the problem you have to analyze if you typed a line jump that varies according to the operating system then you cannot 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 it has to analyze whether the line end has been typed in the internal loop as well.

Had variable initializations at wrong location.

I’ve 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Good night! I had taken a base code and adapted it to my needs, had pointer usage requirements and dynamic allocation, got a little lost in it. But thanks for the help, what do I need to focus on to master this part? I could turn the variable letter to integer and use the characters of the ASCII table instead of ' n'?

  • First master simple logic. Second take something to use pointers in a way that is how you really use it, keep doing this lot of relocations only works in exercise

0

Why don’t you do it like this:

while ( scanf("%...",&...) != EOF )
{
    ......
    ......
    ......
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.