-4

//code for mvt. in this ch did not scan by compiler. ch is used as a condition for loop . Its initial value is 'y' , and if it goes to 'n' , loop breaks. In this code i am asking user if he/she want to continue then press y else n . but don't know why gcc do not wait for scan it. It is a simple code but i can not get the mistake.

    int main(){
    char ch;
    temp=tm;
    ch='y';
    for(i=0;ch=='y';i++){
    printf("enter memory size for process %d",i+1);
    scanf("%d",&m);
    if(m<temp)
    {printf("memory allocated\n"); ms[n]=m; n++;
    temp-=ms[i];
     }
    else 
    {printf("memory not allocated\n"); }
https://stackoverflow.com/users/10404087/rishabh-sharma
    printf("do you want to continue");
    scanf("%c",&ch);
    }
    printf("total memory : %d\n",tm);
    printf("process \t occupied \n");
    for(i=0;i<n;i++)
        printf("%7d \t %8d \n",i+1,ms[i]);
    printf("total externel fregment : %d \n",temp);
    return 0;
    }

1 Answers1

2

You have to use flushall() function that clears all buffers associated with input streams, and writes any buffers associated with output streams.

Added:flushall() isn't C, but a vendor specific extension.

OR

Other alternative is to use space before %c


Example

char ch;
scanf(" %c", &ch);
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31
  • I'd read all `char`s of the stream until `EOF` is detected. – alk Sep 23 '18 at 14:54
  • @alk but I think thats extra overhead. As in this case we know that it is just carriage return which has encountered so why we have to go through the buffer till `EOF` as this will raise time complexity. – Zahid Khan Sep 23 '18 at 14:58
  • @alk: do you mean EOF or EOL (end of line)? I'd suggest EOL is more helpful than EOF, though EOF is not necessarily wrong. – Jonathan Leffler Sep 23 '18 at 15:41