好吧,我必须编写这个程序来询问用户名称并将其插入一个数组然后打印该数组,但它不会打印除 null 之外的任何内容而且我不知道我在做什么我做错了,代码是西类牙语,但函数“insertar”只是插入新名称,listar 必须列出数组中的项目
#include<stdio.h>
#define MAX 5
#include<string.h>
char arreglo[MAX];
int indice;
//prototipo de funcion
int menu (char texto[],int n);
void insertar (char dato);
void listar();
main(){
//variable locales
int opcion;
char dato[50];
indice = -1;
do{
opcion = menu("\n1) Insertar\n2) Borrar\n3) Actualizar\n4) Ordenar\n5) listar\n6) Buscar\n7) Salir\n",7);
switch(opcion)
{
case 1://insertar
if(indice < MAX-1){
printf("Dame el dato a insertar");
scanf("%s", dato);
insertar(dato[50]);
}//fin if
else{
printf("error no hay espacio" );
}//fin else
break;
case 2:
printf("\nBorrar");
break;
case 3:
printf("\nActualizar");
break;
case 4:
printf("\nordenar");
break;
case 5://listar
printf("\nListando\n");
listar();
printf("%s \t ", arreglo);
break;
case 6:
printf("\nBuscar");
break;
case 7:
printf("\nHasta luego...");
break;
}//fin switch
}while(opcion != 7);
}//finn del main
int menu (char texto[], int n){
int opcion;
do{
printf("%s", texto);
scanf("%d",&opcion);
if(opcion <1 || opcion >n){
printf("error: opcion no valida");
}//fin del if
}while(opcion <1 || opcion >n);
return opcion;
}//fin funcion
void insertar (char dato){
indice ++;
arreglo[indice]= dato;
}//fin funcion
void listar(){
char i;
for(i=0; i<=indice ; i++){
printf( "%s \t ", arreglo[i]);
}
printf("\n");
}//fin funcion
最佳答案
创建字符串数组的一种方法是使用二维字符数组。例如代替
#define MAX 5
...
char arreglo[MAX];
...
char dato[50];
你会有
#define MAX 5
#define MAX_LEN 50
...
char arreglo[MAX][MAX_LEN];
...
char dato[MAX_LEN];
下一步是将 scanf
更改为 scanf("%49s", dato);
。这可以防止用户溢出缓冲区。
行 insertar(dato[50]);
应该是 insertar(dato);
以将 dato
数组传递给函数。
最后需要使用strcpy
函数将字符串复制到数组中。
void insertar(char dato[]) {
indice++;
strcpy(arreglo[indice], dato);
}
并且 insertar 方法声明应该变成:
void insertar(char dato[]);
关于c - 它出现在 c 中的字符串数组 (null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447481/