随机选择名称时的奇怪字符 [英] Strange characters when choosing names at random
本文介绍了随机选择名称时的奇怪字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct persona
{
char *nombre;
int edad;
int sexo;
} Persona;
typedef struct
{
int size;
Persona vecPersona[];
} Array;
Array* getArrayInstance()
{
Array *vec;
vec = (Array*) malloc (sizeof(Array));
vec->size = 0;
return vec;
}
void push_back(Array ** vec, Persona tipito)
{
(*vec)->vecPersona[(*vec)->size] = tipito;
(*vec)->size++;
printf("%d-", (*vec)->size);
int newSize = (*vec)->size+1;
Array *tmp = realloc((*vec), newSize*sizeof(Persona));
if(tmp)
*vec = tmp;
else
(*vec)->size--;
}
void mostrarPersonas(Array *vec)
{
int i;
printf("\n\n");
printf("%d", vec->size);
for(i=0; i<vec->size; i++)
{
printf("(%d) Nombre: %s - Edad: %d - Sexo: ", i, vec->vecPersona[i].nombre, vec->vecPersona[i].edad);
if(vec->vecPersona[i].sexo == 0)
printf("Masculino");
else
printf("Femenino");
printf("\n");
}
}
void cargarPersonas(Array **vec)
{
int i, edad, random;
int cantPersonas = 3;
Persona aux;
char hombres[][20] = {"Ramiro","Pedro","Federico","Jose","Antonio","Pablo","Raul","Gustavo","Gonzalo","Airton"};
char mujeres[][20] = {"Mariana","Jennifer","Luz","Roxana","Ana","Sol","Micaela","Romina","Melina","Camila"};
for(i=0; i<cantPersonas; i++)
{
edad = rand()%80+1;
aux.edad = edad;
if( (random = rand()%10) %2 == 0)
{
aux.nombre = hombres[random];
aux.sexo = 0;
}
else
{
aux.nombre = mujeres[random];
aux.sexo = 1;
}
push_back(vec, aux);
}
}
int main()
{
srand(time(NULL));
Array *vecPersonas = getArrayInstance();
cargarPersonas(&vecPersonas);
printf("%d", vecPersonas->size);
mostrarPersonas(vecPersonas);
return 0;
}
代码编译没有错误,但是当我执行它时它会给我带来问题。例如,我在名称字段中输入了奇怪的字符。
示例输出:
The code compiles without errors, but it gives me problems when I execute it. For example I get strange characters in the name field.
Sample output:
Nombre: ?ç!:. - Edad: 25 - Sexo: Maculino
Nombre: #´ç``'' - Edad: 15 - Sexo: Femenino
Nombre: ,.´`$ªº - Edad: 25 - Sexo: Maculino
我使用的是IDE Codeblock版本13.12
I am using the IDE Codeblock version 13.12
推荐答案
ªº - Edad :25 - Sexo:Maculino
ªº - Edad: 25 - Sexo: Maculino
我使用的是IDE Codeblock版本13.12
I am using the IDE Codeblock version 13.12
你的问题是,名称数组超出范围。快速解决方法是使其全球化。正确的方法是为名称分配缓冲区或字符串对象。
我的提示是使用std:string。
Your problem is, that the names array goes out of scope. A quick fix is to make it global. The correct way is to allocated buffers or string objects for the names.
My tip is to use std:string.
这篇关于随机选择名称时的奇怪字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文