我有这个代码,我想知道为什么我的代码跳过scanf ...
#include <stdio.h>
char nombre[20];
int tipo;
int edad;
int dias;
int repetir=0;
int main()
{
while (repetir==0){
int error=0;
do{
printf("Diga su Nombre: ");
scanf("%19[^\n]", nombre);
printf("Diga el tipo de Sala: ");
scanf("%d", & tipo);
printf("Diga la edad del Paciente: ");
scanf("%d", & edad);
printf("Dias de Hospitalizacion: ");
scanf("%d", & dias);
if ((tipo>4) || (tipo<0) || (edad<0) || (dias <0) ){
printf("Eror al ingresar los datos");
} else {
error = 1;
}
}
while(error==0);
printf("¿Algun otro paciente? SI=0 NO=1");
scanf("%d", &repetir);
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)
它只是一个简单的代码,但是当我运行代码时出现如下代码:
Diga su Nombre: (Name with spaces)
Diga el Tipo de Sala (Integer Number)
Diga la edad del Paciente (Integer Number)
Dias de Hospitalizacion (Integer Number)
//Check For errors
¿Algun otro paciente? SI=0 NO=1 (Pressing 0 To repeat)
//Repeat
Diga su Nombre: Diga el Tipo de Sala
....
....
Run Code Online (Sandbox Code Playgroud)
代码不再向我询问字符串数据,我真的不知道在这种情况下我要做什么......非常感谢你的帮助!
这就是我试过的......但只是冻结了
// .....
scanf("%d", & dias);
//Dont really know what to do here :S
int c; while ( (c = getchar()) == '\n' && c != EOF ) { }
if ((tipo>4) || (tipo<0) || (edad<0) || (dias <0) ){
Run Code Online (Sandbox Code Playgroud)
在里面main(),该行char nombre[]= {0};声明了一个大小的数组1.然后你用它读入它scanf,这会溢出缓冲区,导致未定义的行为.
数组不会在C中自动增长,它们具有固定的大小,您在定义它们时必须分配它们.(由于您将大小留空,因此通过计算初始化程序的数量来计算大小).
修复示例:
char nombre[50];
// ...
scanf("%49[^\n]%*c", nombre);
Run Code Online (Sandbox Code Playgroud)
NB.全局变量char nombre[];是不同的变量来main的nombre,而你目前没有使用它,所以我建议删除这两个中的一个(并给予剩下的一个大小如50).
如果您不止一次执行此循环,还有另一个问题.当您使用scanf("%d"...时,它会提取整数的字符,但它也不会提取换行符.所以下次你来scanf("%[......时,会在那里读取换行符.
要解决此问题,您需要在循环结束时手动使用换行符,例如
scanf("%d", &repetir);
while ( getchar() != '\n' ) { }
Run Code Online (Sandbox Code Playgroud)
可能也是这样做的scanf("%d", & dias);.从技术上讲,它应该是int c; while ( (c = getchar()) != '\n' && c != EOF ) { }一个不是问题的交互式程序.
此外,这%*c是多余的,你可以做到scanf("%49[^\n]".为了正确,此时您还可以丢弃剩余的线.
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |