我正在做一个程序,要求用户输入姓名和ID号......然后我添加了一个搜索功能,例如搜索名称“bob”,它说“Bob在阵列位置x找到了ID: XXXXX“
我的问题是代码中的“ID:xxxx”部分给了我随机数字......它应该是例如1234但它给我的东西像4210832
这是代码
void search_surname()
{
int index, found=0;
char surname_to_find[10];
printf("Please enter the student surname to search for\n\n");
gets(surname_to_find);
fflush(stdin);
system("cls");
for(index=0;index<height_of_array;index++)
{
if(strcmpi(surname_to_find, surname[index]) == 0)
{
found=1;
system("cls");
printf("%s found in array position %i, with the ID: %i \n\n", surname_to_find,
index+1, id[array_index] );
getch();
我不是100%肯定为什么它会给我随机数
感谢。
答案 0 :(得分:1)
将id[array_index]
更改为id[index]
答案 1 :(得分:1)
您发布的代码如此不完整,以至于无法指出确切的答案。相反,这是一种解决问题的方法:
id[array_index]
代替id[index]
时很奇怪,因为index
是for循环中的变量。 (array_index
未在您的函数中定义;它是全局的吗?请避免使用全局变量!)。id
被填充,甚至被声明。确认它已正确填充。使用id
而不首先填写值将打印出奇怪的东西(未初始化)。调试器应该确保正确填充它。否则,只需将其循环并打印出来即可。最后一件事:C有结构。没有理由使用这样的多个数组。
struct surname_info {
unsigned int id;
const char *surname;
};
⋮
struct surname_info surnames[10];
surnames[0].id = 1234;
surnames[0].surname = "Bob";
/* etc */