scanf一直被跳过

在函数“leerdatos”中格式化“direccion”的scanf之后,它跳过第二个’for’循环中的“nro_corredor”。

我已经阅读了相关问题,但仍然没有得到答案。

我该怎么做才能解决它?

#include  typedef struct { int minutos; int segundos; } s_tiempo; typedef struct { int nro_corredor; // guarda nro de corredor s_tiempo tiempo; // guarda el tiempo que tardo el corredor } carrera; typedef struct { int nro_corredor; // guarda nro de corredor char apellido[20]; char nombres[20]; char direccion[30]; } datos; datos leerdatos(); //declaro la funcion leer int main (void) { int cp; //cantidad de participantes. datos aux; printf("Ingrese la cantidad de participantes: "); scanf("%d",&cp); datos corredor[cp]; carrera carreras[cp]; printf("A continuacion, ingrese los datos de los corredores: \n"); for(int i=0;i<cp;i++){ aux = leerdatos(); corredor[i] = aux; } } datos leerdatos(void) { datos participante; printf("\nIngrese el numero de corredor: "); scanf("%d",&participante.nro_corredor); printf("\nIngrese el apellido:\n"); scanf("%s",participante.apellido); printf("\nIngrese los nombres:\n"); scanf("%s",participante.nombres); printf("\nIngrese la direccion:\n"); scanf(" %s\n",participante.direccion); return(participante); } 

您面临的另一个问题是需要在调用scanf刷新输入缓冲区(stdin) 。 正如chux所指出的那样, scanf不会消耗换行符'\n' ,而是将它留在输入缓冲区中作为下一个字符读取。 每次使用scanf后刷新输入缓冲区总是好的, 特别是在多次调用scanf时。 刷新输入缓冲区的一种简单方法是:

 int c = 0; /* test int for getchar */ ... scanf("%d",&cp); do { c=getchar(); } while ( c != '\n'); /* flush input buffer */ 

注意: fflushf不会清除stdin剩余的字符。

scanf()使用不正确

 // scanf(" %s\n", ... scanf("%s", ... 

"%s"之后的'\n''\n'空白区域指示scanf()查找空白区域,直到跟随非白色空格。 那个非白色空间被放回到stdin 。 这可能意味着OP必须为第4个输入输入2 Enter

应始终检查scanf()返回值以查看它是否符合预期。

 // scanf("%d",&participante.nro_corredor); if (scanf("%d",&participante.nro_corredor) != 1) Handle_Error(); 

scanf() "%s""%d"之前放置一个空格没有区别。 这些说明符将消耗可选的空格,即使没有前导" "

建议使用fgets()来读取用户输入(这是邪恶的 ),然后使用sscanf()strtok()strtol()等进行解析。


注意:除了扫描集"%[...]" ,像' ''\t''\n'和其他类似' '空格都执行相同的操作 :它们消耗任意数量的空白。 扫描scanf(" %s\n",... '\n' scanf(" %s\n",...不扫描1 '\n' 。它扫描任意数量的任何空白区域。它将继续扫描空白区域,包括多个Enter直到EOF或输入非空格为止。然后将非白色空间作为下一个要读取的字符放回到stdin中。

 #include  struct s_tiempo { int minutos; int segundos; }; struct carrera { int nro_corredor; // guarda nro de corredor struct s_tiempo tiempo; // guarda el tiempo que tardo el corredor }; struct datos { int nro_corredor; // guarda nro de corredor char apellido[20]; char nombres[20]; char direccion[30]; }; bool leerdatos( struct datos *); //declaro la funcion leer int main (void) { int cp; //cantidad de participantes. printf("Ingrese la cantidad de participantes: "); if( 1 != scanf(" %d",&cp) ) { perror( "failed getting participantes using scanf()"); return( 1 ); } // implied else struct datos corredor[cp]; struct carrera carreras[cp]; // should get compiler warning due to this not being used printf("A continuacion, ingrese los datos de los corredores: \n"); for(int i=0;i