Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

c - loop 2 taking input automatically

My code is behaving weirdly. In loop 1 it is working perfectly but in loop 2 it is automatically printing ASCII value 10. please help!.

#include<stdio.h>

int main(){
    char c;
    int loop =1;

    do{

        printf("
Loop = %d
Write character of which you want to find acii values: ", loop);
        scanf("%c", &c);
        printf("
ASCII value of %c is %d.", c, c);
        loop++;

    }while(c != 'Z');

    printf("
******END*****");
    
    return 0;

}
question from:https://stackoverflow.com/questions/65898001/loop-2-taking-input-automatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

10 is ASCII for newline. You are reading whitespace, which you can avoid by using

scanf(" %c", &c);

Note the additional blank before the character specifier. It instructs scanf to ignore white space.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...