Jeffrey
Jeffrey

Reputation: 139

Run-Time Check Failure #2 - Stack around the variable 'char' was corrupted

#include <stdio.h>
int main()
{
    char ch;
    int i;

    for (i = 1; i <= 5; i++) {
        printf("Enter a Character: ");
        scanf("%s", &ch);

        if ((ch >= '0') && (ch <= '9'))
            printf("The character is a numeral\n");
        else if ((ch >= 'A') && (ch <= 'Z'))
            printf("The character is in upper case\n");
        else if ((ch >= 'a') && (ch <= 'z'))
            printf("The character is in lower case\n");
        else
            printf("The character is a special character\n");

    }
    return 0;
}

I want to read a character input from user and display the character type. However everytime after running the last scan of the program, it will have a debug error. I am using Visual Studios C++ 2010 Express.

Run-Time Check Failure #2 - Stack around the variable 'ch' was corrupted.

Please help!

Upvotes: 1

Views: 1344

Answers (2)

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

In scanf,

If you want to the single character you have to use the control string %c. %s for getting the string.

So change the scanf into

scanf(" %c", &ch);

Upvotes: 1

Gopi
Gopi

Reputation: 19874

To scan a char use

scanf("%c", &ch);

Using wrong format specifier will lead to undefined behavior.

Please make sure you ignore the newline char and do it by placing a space before %c

scanf(" %c", &ch);

The space before the %c will make sure that the newline char in the buffer gets ignored. i.e space gobbles the newline char.

Upvotes: 4

Related Questions