Adding characters to an array as integers in C

I am trying to add integers to an array in C. However I'm reading characters in from a file, so I have to convert them to integers first. For some reason my program wont even start up now before it stops working. I think it is a conversion problem but I am new to C.

new edit code:

#include <stdio.h> #include <stdlib.h> int main (void) { FILE* fp; const char filename[] = "test.txt"; char ch; int num[1000]; int j = 0; char temp; fp = fopen(filename, "r"); if( fp == NULL ) { printf( "Cannot open file: %s\n", filename); exit(8); } while(!feof(fp)) { temp = fgetc(fp); num[j] = temp - '0'; j++; } printf("First in the array is: %d, last is; %d", num[0], num[999]); fclose(fp); return EXIT_SUCCESS; }

test.txt

731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511 125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749 303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243 525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474 821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142607690042 242190226710556263211111093705442175069416589604080719840385096245544436298123098787992724428490918884580156166097919133875499200524063689912560717606 0588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450

Someone to point me in the right direction would be great.

-------------Problems Reply------------

I am rephrasing my entire answer after you added the contents of test.txt.

Instead of

while(!feof(fp))
{
temp = fgetc(fp);
num[j] = temp - '0';
j++;
}

Change to

while(!feof(fp)&& (j<1000))
{
temp = fgetc(fp);
if ( temp != EOF && ( temp>='0' && temp<='9') ) // To filter out non-numbers and also the last EOF
num[j++] = temp - '0';

}

And instead of

printf("First in the array is: %d, last is; %d", num[0], num[999]);

Change to

printf("First in the array is: %d, last is; %d", num[0], num[j-1]); // j-1 so that it works even when there are less than 1000 numbers and to keep it generic

And your done!

You cannot dynamically allocate an int array in C like this, so

int num[count]

will not work. Use a maximum value or dynamic allocation using malloc.

Also you cannot pass a single char to atoi, you have to pass a 2-element char array with the second element being 0, or you could just use

num[j] = temp - '0';

Also checking fp for EOF in the second while loop is wrong, use feof(fp) or temp != EOF

Hope this helps you a bit to get it working.

The following application works and gives the following output (in a textfile containing 1 3 5 5565)

int main (void)
{
FILE* fp;
const char filename[10] = "test.txt";
char ch;
int count = 0;
int num[100];

fp = fopen(filename, "r");
if( fp == NULL )
{
printf( "Cannot open file: %s\n", filename);
exit(8);
}

while (fscanf(fp, "%d", &num[count]) !=EOF){
count++;
}

rewind(fp);

printf("Text file contains: %d\n", count);
printf("First in the array is: %d, last is; %d\n", num[0], num[count-1]);

fclose(fp);
system("pause");
return EXIT_SUCCESS;
}

if you want the array to be dynamicly sized, you need to loop thru the elements and count them, before adding them, just like you did in your example in the main code. And instead of while (fscanf(fp, "%d", &num[count]) !=EOF){ you use a temp counter to index the elements

Hope this helps

Category:c# Views:0 Time:2012-03-06

Related post

  • Array of Integers vs Array Of Characters 2014-12-11

    I am aware that an array of characters (basically a string) always terminates with the null character. I was just wondering what does an array of integers end with. --------------Solutions------------- An array of characters does not end with a 0-ter

  • Most efficient way to store large arrays of integers in localStorage with Javascript 2012-04-12

    *"Efficient" here basically means in terms of smaller size (to reduce the IO waiting time), and speedy retrieval/deserialization times. Storing times are not as important. I have to store a couple of dozen arrays of integers, each with 1800 values in

  • Three dimensional arrays of integers in C++ 2008-09-15

    I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using STL techniques such as vectors. Essentially I want my integer array dimensio

  • How do I send an array of integers over TCP in C? 2009-03-23

    I'm lead to believe that write() can only send data buffers of byte (i.e. signed char), so how do I send an array of long integers using the C write() function in the sys/socket.h library? Obviously I can't just cast or convert long to char, as any n

  • Functions to compress and uncompress array of integers 2009-10-20

    I was recently asked to complete a task for a c++ role, however as the application was decided not to be progressed any further I thought that I would post here for some feedback / advice / improvements / reminder of concepts I've forgotten. The task

  • Convert an array of integers for use in a SQL "IN" clause 2009-11-13

    Surely there is a framework method that given an array of integers, strings etc converts them into a list that can be used in a SQL "IN" clause? e.g. int[] values = {1,2,3}; would go to "(1,2,3)" --------------Solutions------------- var inClause = "(

  • Parse CSV string into Array of Integers 2009-11-18

    I have a text box field inputs 123,145,125 I to separate this field into an array of integers. And validate this field true or false if everything is parsed right. CODE: private bool chkID(out int[] val) { char[] delimiters = new char[] { ',' }; stri

  • Transform an array of integers into a string 2010-01-13

    A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string. Example: int IArray = {1, 2, 3}; // should be coverted into "123" Is there a direct function a

  • array of Integers in embedded x86 assembly 2010-10-21

    I am trying to acces values from an array of integers and have been trying for hours with no luck. Here is my code so far: All I am trying to do is acces the values in the array "arr", i have seen how to do it with characters but not with integers. i

  • Ruby: How do I convert a string (ARGV) representation of integers and ranges to an array of integers 2010-10-22

    In Ruby, how can I take an array of tokens representing either integers or ranges and parse them into an array of integers that include each integer and each element in each range? Example: Given input [ "5", "7-10", "24", "29-31"] I'd like to produc

  • Parsing String to Array of Integers 2010-11-23

    I'm looking for a way to convert a string with specified dividers (such as slashes or spaces) into an array of the integers those dividers separate. For example, if the user inputs 12/3/875/256, I need to retrieve the array {12, 3, 875, 256}. Ideally

  • Turning an array of integers into an array of nonnegative integers 2011-06-01

    Start with an array of integers so that the sum of the values is some positive integer S. The following routine always terminates in the same number of steps with the same results. Why is this? Start with an array x = [x_0, x_1, ..., x_N-1] such that

  • Storing arrays of integers in database 2011-06-27

    I am creating a database that will store 100.000 (and probably more in the future) users. While this obviously happens in a table with 1 row per user, every user can (and will) store hundreds of items. In programming language this would mean the user

  • Given an array of integers. Find the LARGEST subarray with the MAXIMUM sum 2011-08-23

    Hi I am preparing for an interview code test and I stumbled across this question. I tried attempting it in C#, below is my embarrasing answer which I don't even know if it's right but mostly I guess not, could someone please kindly provide me with th

  • counting characters in char array 2011-09-09

    i wrote following code to count occurance of characters in given char array #include <iostream> #include <string> using namespace std; int main(){ char f[]={'a','a','b','c','c','d','d','f','e','e'}; int n=sizeof(f)/sizeof(char); char max=

  • Passing an array of integers from an AppWidget to a preexisting RemoteViewsService to be rendered by the RemoteViewsFactory 2011-09-09

    I have an AppWidget that has a StackView contained within it. Along with the AppWidget, I have a service that is started when a user adds my AppWidget to their homescreen that polls for new data every two hours. When the service finds new data, I nee

  • Converting a range or partial array, in the form "3-6" or "3-6,12", into an array of integers, like 3,4,5,6,12 2011-10-08

    I'm a little baffled by this one, and I'm struggling to find any similar examples online at the moment. Working in PHP, I want to take input, probably from a form field, of a either a "list of values", a "range" or a combination of the two, in the fo

  • Adding elements of an array 2012-01-12

    I have a ten element array of integers. I want to sum the elements by group, so for instance I want to add the value at element 0 with the value at element 1, then with the value at element 2, then 3, and so on through to element 9, then add the valu

  • Remapping an array of integers 2012-02-18

    I have an array of integers from [0 .. 255]. I'd like to modify the array so that there are still 256 numbers, but the numbers start from 100 and move up to 255. This means that many integers will be repeating (i.e. [100,100,101,101,102 ...]) Any ide

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.141 (s). 11 q(s)