开发者

how to form an array of numbers , taken input from a file in C

开发者 https://www.devze.com 2023-01-01 11:43 出处:网络
The program should be able to make an array of numbers from a text file which reads like this The data is given as this

The program should be able to make an array of numbers from a text file which reads like this The data is given as this 123 2132 1100909 3213 89890

my code for it is

char a;
char d[100];
char array[100];
a=fgetc(fp) // where fp is a file pointer 

if (a=='')
{
d[count1]='/0';
strcpy(&array[count],d);
count=count+1;
memset(d,'\0',100)
count1=0;
}

else 
{
d[count1]=a;
count1=count1+1;
}
a=fgetc(fp);

i am getting segmentation fault now . want to store each number in the array so that i can do sortin开发者_C百科g on it


Your (first) problem is here:

d[count1]='/0';
strcpy(&array[count],d);

You have written '/0', which isn't what you think it is. Assuming you meant '\0' (a null char literal), then you appear to be trying to manually terminate the string d before calling strcpy(). The problem is that what actually gets written to d is not a null byte, and so d is not null-terminated, and then strcpy() goes off and starts reading random memory after it, and copying that memory into array, until either the reading or the writing ends up outside of memory you're allowed to access, and you get a segmentation fault.

You also have some confusion about that array is. It's declared as an array of 100 chars, but you're treating it like it's an array of strings. Perhaps you meant to declare it as char *array[100] ?


Hmm...as a first approximation, to read a single number, consider using fscanf("%d", &number);. To store the numbers you read, you'll probably want to create an array of numbers (e.g., int numbers[100];). To read more than one number, use a loop to read the numbers into the array.

Sidenote: fscanf isn't particularly forgiving of errors in the input (among other things) so for production code, you probably want to read a string, and parse numbers out of that, but for now, it looks like you probably just need to get something that works for correct input, not worry about handling incorrect input gracefully.


Is this actually how the code is written?

In d[count1]='/0'; I think you mean d[count1]='\0'; (already mentioned by Daniel Pryden).

There is also a semicolon missing at the end of memset(d,'\0',100)

0

精彩评论

暂无评论...
验证码 换一张
取 消