Question

I have this code, which I expect from to read a single character from user, then re-print it, then realloc'ing new memory to store the next character that user will enter; all this repeating until the user enters the '1' character. However, my program does nothing until the user presses 'return', then echoes back the entire string. Why does it behave like this?

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

int main()
{
    char *s = (char *)malloc(sizeof(char));
    int i = 1 ;
    do
    {
        scanf(" %c",s+i-1);
        printf("%c" , *(s+i-1));
        i++ ;
        s = (char *)realloc(s , sizeof(char)*i);
    }while(*(s+i-1) != '1');
    printf("\n\n %s" , s);
    return 0;
}

This is what I expect:

h // input from user
h // the output
w // input from user
w // output from user

But this is what I get:

what // input from user
what // output 

I tried to replace scanf by getchar, but that doesn't help.

Was it helpful?

Solution 2

stdin buffers characters until the user presses the enter key , so it will not deal , with single character.

OTHER TIPS

Input is buffered and won't be delivered to your program until the user hits return. See this question or this question.

Your use of malloc/realloc has nothing to do with it.

That is because the standard output stream stdout is line-buffered. This means that output won't appear on the screen until a newline '\n' is output or the buffer is full at which the buffer is flushed. Also, you should not cast the result of malloc or realloc. You should also check for the result of malloc or calloc for NULL.

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

int main(void) {
    char *s = malloc(sizeof *s);
    if(s == NULL) {
        printf("not enough memory to allocate\n");
        return 1;
    }
    int i = 0;
    char *temp;
    do {
        scanf("%c", s + i);
        printf("%c\n", *(s + i));
        i++;
        temp = s;
        s = realloc(s, i * sizeof *s);
        if(s == NULL) {
            printf("not enough memory to allocate\n");
            s = temp;
            // handle it
            // break;
        }
    } while(*(s + i) != '1');
    printf("%s\n", s);

    // after you are done with s, free it
    free(s);

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top