I’ve got homework, to take phone numbers from a text file, and put it into an array…
here is what I wrote, though it puts nothing on it…
the loop is that as long as theres text in the .txt files, read it into the array…
void get_phones(int *phones)
{
FILE *fp;
fp = fopen("phones.txt", "rt");
if (fp == NULL)
{
printf ("Error\n");
}
else
{
while (fscanf(fp, "%d\n", &phones) > 0)
{
fscanf(fp, "%d\n", &phones);
}
}
}
Lastest update:
For testing:
please put the following code in your
main(),and change the number 10 to the # of lines you have in the file. To compute the upper bound automatically you can try to change the return type ofget_phonestointand put a counter in the while-loop.You need deference a pointer in order to print the actual value. Otherwise you are printing the address stored in the pointer. And
phones, besides being the name of an array, it is a pointer pointing to the first element in the array in its nature. For more info on pointer and array, see this tutorial.Assume that you are using a 32-bit machine
The phone numbers I put in my textfile is the following:
22121222345
678139199
111111111
Note that 22,121,222,345>=2,147,483,647, which is the maximum number an int can represent. (For
unsigned intit is 2^32-1). Now if we try to run the following code:The list of number printed on terminal are:
646385865
678139199
111111111
The first number saved in the array is totally random! Why? because it is too large for an integer and it overflows.
Now if we try the following version:
The list of number printed on terminal are:
22121222345
678139199
111111111
Why does it work? Because the type
long longcan store number up to 2^63-1 = 9,223,372,036,854,775,807Tested working version. Change the data type to
long longif you want.!! The problem with your code is that you are passing the wrong thing to the
fscanf.phonesis already a pointer — it is pointed to the starting point of the array. when you writephone++, it passes the current pointer to fscanf, and increase the pointer by one, which moves the pointer to the next slot in the integer array.Also, although
fscanfwill return the number of items it scanned, in your while loop condition, the scanning is already performed. So you don’t need to call it second time in the body of the while loop5195551234 this number is still too large for
unsigned long, unfortunately. Because for 32-bit machine, bothintandunsigned longhas the max value $2^{32}-1$. Check out wikipedia if you need more information on this. Instead you needlong longif you are running your code on 32-bit machine, otherwise it will overflow and store incorrect data.