问题描述
#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;
}
我想读取用户的文字输入和显示字符类型。然而在运行程序的最后一次扫描之后,每次,就会产生一个调试错误。我使用视觉工作室C ++ 2010例preSS。
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.
运行时检查失败#2 - 围绕堆栈变量'通道'已损坏
Run-Time Check Failure #2 - Stack around the variable 'ch' was corrupted.
请帮帮忙!
推荐答案
要扫描一个char使用
To scan a char use
scanf("%c", &ch);
使用错误的格式说明会导致不确定的行为。
Using wrong format specifier will lead to undefined behavior.
请确保您忽略换行字符,并在%C
Please make sure you ignore the newline char and do it by placing a space before %c
scanf(" %c", &ch);
在%C
之前的空间将确保在缓冲区中的换行字符被忽略。即鲸吞空间换行字符。
The space before the %c
will make sure that the newline char in the buffer gets ignored. i.e space gobbles the newline char.
这篇关于运行时检查失败#2 - 围绕堆栈变量'炭'已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!