-
Loops won't iterate
Hey folks,
Working on a project here and I can't figure out why my loop won't iterate within my function. It's the for loop at the end. Could you take a look?
Code:
//Load File
void load(entry *phonebook, int numOfEntries) {
FILE *pRead;
double totalSize;
int num, m = 0;
//Begin Reading
pRead = fopen("phoneBook.txt", "r");
if(pRead == NULL) {
printf("\nFile Can't be Opened\n");
}// End if
//Else Read Sucessfull
else {
//Find File Total Size
fscanf(pRead, "%d", &totalSize);
printf("\nGot total size. Total size is %d\n", totalSize);
//reallocate memory
entry *temp = realloc(phonebook, (totalSize+1) * sizeof(entry));
//Debugging memory allocation error
if (temp == NULL){
printf("\nMemory Allocation Error in LOAD FILE\n");
}//End Debugging If
//Memory allocation successfull
else {
phonebook = temp;
printf("\nMemory Allocation Sucessful\n");
}//End Else
for(m=0; m < totalSize; m++){
printf("1st time: i is %i, totalSize is %d\n", m, totalSize);phonebook[i].fName);
printf("2nd time: i is now %i, totalSize is %d\n", m, totalSize);
}
printf("out of loop: i is now %i, totalSize is %d\n", m, totalSize);
} //End Read Sucessful Else
fclose(pRead);
}// End Load File
-
You've made totalSize a double (floating point) but you are using it as if it's an int. It should probably be an int.
-
thanks.
I'm also trying to copy the lines from my file into a structure in an array. Each line in the file is formatted word,word,word
I originally tried to just pick up everything between either spaces or commas (originally had spaces between words instead of commas) and copy each word into its section of the structure, but that's not working. I also tried to pick up the entire line and copy it into a variable, and then print that, but that just results in a single character being printed.
Ideas on how to take each word from the line and put them into my structure?
Code:
char v1;
while (i < numOfEntries) {
printf("m is %i, totalSize is %d\n", i, numOfEntries);
fscanf(pRead,"%c", &v1);
printf("Found contact number %i\n", i);
printf("contact is %c\n", &v1);
// fscanf(pRead,"%s %s %s", phonebook[i].fName, phonebook[i].lName, phonebook[i].phoneNum);
i++;
}
-
How about this:
Code:
while (i < numOfEntries) {
fscanf(pRead, "%s ,%s ,%s",
&phone[i].fName,
&phone[i].lName,
&phone[i].number);
i++;
}
-
Another problem you have is if realloc moves the memory to somewhere else, the caller has no idea where it moved to.