0 votes

Read a line entered and compare it character by character with another character previously entered

Example of screen output:

Ingrese la letra a buscar

c

Ingrese la frase:

como cocinas

+omo +o+inas

It is not necessary to save anything or read everything first and then print, so I indicated that it is not necessary to do this with arrays, or string.

What I don't understand is how leo character by character, the sentence entered without using arrays. this is what I did until now.

int main()
{
    char letra;
    char oracion;


    printf("Ingrese el caracter a buscar:\n");
    letra=getchar();
    getchar();

    printf("Ingrese la oracion:\n");
    oracion=getchar();
    getchar();


    while(oracion!='.'){
        if(oracion==letra){
            oracion='+';
            printf("%c", oracion);
        }
    }


    return 0;
}

1voto

PaperBirdMaster Points 24910

It is not necessary to save anything or read everything first and then print

You have deceived. Read it all, process it, and print it out is the right way to do it. The restrictions that you put on are absurd and inconsistent.


Luckily, in spite of how absurd the petition is easy to program. The input of data in C works by using buffers. You can extract data from the input buffer with different functions between them: the one that you're already using getchar.

The function getchar removes a character from the input buffer (the sequence FIFO), not having anything to extract returns EOF, so we can read the input and write the output without saving anything and without the use of arrays in the following way:

int main(void)
{
    char c;
    while ((c = getchar()) != EOF)
        printf("%c", c);

    return 0;
}

Therefore, to replace a letter that is entered, it can be done in the same loop:

int main(void)
{
    printf("Introduce una letra");
    char letra;
    scanf("%c", &letra);

    printf("Introduce una frase");
    char c;
    while ((c = getchar()) != EOF)
        printf("%c", c == letra ? '+' : c);

    return 0;
}

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X