我一直在練習C幾個星期,現在我試着弄清楚我的代碼中可能做了什麼錯誤。不返回期望值的函數
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct accounts{
char unList[32];
int pinList;
float amtList;
}account;
int isValid(char inputUN[], account acount[]);
void initialize(account acount[], char unList[][10], int pinList[], float amtList[], int size);
int main(int argc, char *argv[]) {
int size = 10;
account newAccs[size];
char unList[][10] = {"franklin", "woods", "phillips", "gomez", "burns", "porter", "griffin", "spencer", "hanson", "johnson"};
char inputUN[32];
int index;
initialize(newAccs, unList, pinList, amtList, size);
printf("Enter Username: ");
scanf("%s", inputUN);
index = isValid(inputUN, newAccs);
printf("%d\n", index);
return 0;
}
void initialize(account acount[], char unList[][10], int pinList[], float amtList[], int size){
int index;
for(index = 0; index < size; index++){
strcpy(acount[index].unList, unList[index]);
acount[index].pinList = pinList[index];
acount[index].amtList = amtList[index];
}
}
int isValid(char inputUN[], account acount[]){
int index;
int y;
for(index = 0; index < 10; index++){
if (strcmp(acount[index].unList, inputUN) == 0){
y = index;
}else{
y= -1;
}
}
return y;
}
什麼我真的想在這個節目做的是該程序要求輸入用戶名輸入引腳然後檢查是否兩者在結構,然後將它顯示了一些量,但我已經忽略,則的代碼,因爲我的問題是在isValid()
功能的休息...
int isValid(char inputUN[], account acount[]){
int index;
int y;
for(index = 0; index < 10; index++){
if (strcmp(acount[index].unList, inputUN) == 0){
y = index;
}else{
y= -1;
}
}
return y;
}
在這個函數假定
返回元素的索引;如果該用戶名是在結構,否則返回-1
。如果我在else if
聲明中添加註釋,它會很好用。但是,如果沒有,即使我輸入了正確的元素,它總是會返回-1
。
我可能做錯了什麼?
P.S.對不起,如果我的問題太長,我對Stacks Overflow很陌生
你的'initialize'函數在哪裏? – haccks
哦,對不起..我會添加它... –
你有沒有試過把一個斷點放到y = index來查看它是否被分配了一個值?同樣在分配之後,您應該打破循環或下一個可以將y重新分配給-1。 – koksalb