Chris_Nk
Chris_Nk

Reputation: 1

scanf is causing my code to run on forever

I was trying to use scanf but when I run the code the code goes on forever. And when I stop the code I get

[Done] exited with code=1 in 28.291 second

My question is what am I doing wrong? Here is the code I was trying to execute. My editor is VS code 1.21.0.

#include <stdio.h>
#include <string.h>

int main(){
    char midInitial;

    printf("What is your middle initial? ");

    scanf(" %c", &midInitial);

    printf("Middle inital &c ", midInitial);
}

Upvotes: 0

Views: 2286

Answers (3)

hamed talasaz
hamed talasaz

Reputation: 11

go to code-runner extention setting and make sure <Code-runner: Run In Terminal> checked

Upvotes: 1

chqrlie
chqrlie

Reputation: 145287

The code does not run forever, it is waiting for the user to complete the input. Standard input is line buffered, so the user must type enter after the character for scanf() to process it. It will skip any white space characters, store the first non white space character into midInitial and return 1.

Another possible explanation is the environment you use does not support console input. Run your program from shell interpreter window in Windows.

There is another problem: the format "Middle inital &c " is incorrect, use % for conversion specifiers.

Here is a corrected version:

#include <stdio.h>

int main() {
    char midInitial;

    printf("What is your middle initial? ");
    if (scanf(" %c", &midInitial) == 1) {
        printf("Middle initial: %c\n", midInitial);
    }
    return 0;
}

Upvotes: 1

Amit Prajapati
Amit Prajapati

Reputation: 41

int main(){ char midInitial;

printf("What is your middle initial? ");

scanf(" %c", &midInitial);

printf("Middle inital %c ", midInitial); (see it should be %c) }

Upvotes: 0

Related Questions