Thread: reading integers into arrays from text files

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    3

    reading integers into arrays from text files

    hi, am just starting to learn the c language and have just come accross arrays; im designing a program that will read integers from a text file then hold the values into arrays and finaly add them together, the numbers in the text file will be up to 20 digits long but they may be less and two sets of digits will be on the same line e.g the text file could look like this:

    1234567 123456789101112
    1234567898745 12545877

    the first set of nubers on the top line would be read into the first array then the second set after the space would be read in to the the second array then the values would be added together in a 3rd array and printed on the screen, this process would then start again on the second set of numbers and do the same untill there arnt any more numbers in the text file,

    so far i have made a loop that will read the first set of numbers into the first array:

    ( i=0; i<20; i++)
    {
    if ( i == " ")
    break;
    }
    this should read the first numbers in and terminate when it reaches 20 digits or the space, but thats as far as i have got, i dont know if this will actually work and am not sure how to make a loop to read the second set of numbers and then how to get them to add up snd print out, I would be very gratful the books I have only show how to read text in so i am a bit stuck
    thanks for reading

    this is everything i have so far:
    #include <stdio.h>

    main ()
    {

    int *inf_ptr;
    int array1[20];
    int array2[20];
    int array2[20];
    int i;

    infptr = fopen("mydata.txt", "r");


    if (infptr==NULL)
    {
    printf(" cannot open file for reading");
    }
    else
    { for (i=0; i<20; i++)
    {
    if ( i == " ")
    break;
    }



    return 0;
    }
    Last edited by c_beginner; 08-04-2004 at 04:09 PM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    There's a couple of fundamental flaws here. The type int is generally 32 bits wide meaning it can only hold numbers up to 2^32 (2^31 if it's a signed int). An int isn't always 32 bits wide. It's not actually guaranteed to be anything (except for in relation to other types). Common sizes in use today are 16 bits, 32 bits, and 64 bits. Anyway, your compiler is probably using 32-bit ints. A 20 digit number is far larger than this. This is what is referred to as an "overflow". So that's one thing you're going to want to keep in mind and check when writing this thing.

    I'm also not quite sure about adding together 2 numbers from 2 arrays. You want to add all 4 numbers together?

    Anyway, here's a program that will read 2 sets of 2 numbers in from a text file and store them in 2 arrays for you:
    Code:
    $ cat foo.c
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
      FILE *fp;
      int array1[2];
      int array2[2];
      char buf[128];
    
      fp = fopen("mydata.txt", "r");
      if(fp == NULL)
      {
        puts("Cannot open file for reading");
        exit(EXIT_FAILURE);
      }
    
      fgets(buf, sizeof(buf), fp);
      sscanf(buf, "%d %d", &array1[0], &array1[1]);
      fgets(buf, sizeof(buf), fp);
      sscanf(buf, "%d %d", &array2[0], &array2[1]);
    
      fclose(fp);
    
      printf("Set 1 - 1st: %d, 2nd: %d\n", array1[0], array1[1]);
      printf("Set 2 - 1st: %d, 2nd: %d\n", array2[0], array2[1]);
    
      return 0;
    }
    Here's the contents of mydata.txt:
    724982 29384
    2934 29840
    And here's the results of running the program:
    $ ./foo
    Set 1 - 1st: 724982, 2nd: 29384
    Set 2 - 1st: 2934, 2nd: 29840
    If you have specific questions I'll be happy to answer them.

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    3
    thanks for replying, since i posted i did a bot more work on it, but i seem to using a different method than you this is what i have:
    #include <stdio.h>

    main ()
    {

    int *inf_ptr;
    int array1[20];
    int array2[20];
    int array3[20];
    int i;


    infptr = fopen("mydata.txt", "r");


    if (infptr==NULL)
    {
    printf(" cannot open file for reading");
    }
    else
    {
    for (i=0; i<20; i++)
    {
    if (fptr == " ")
    break;

    fscanf(fptr,"%d", array1[i]);
    }
    {
    for (i=0; i<20; i++)
    {
    if ( fptr == " ")
    break;

    fscanf(fptr,"%d", array2[i]);
    }
    }

    return 0;
    }
    does this make any sense to you, its atill a way actually working but it seems to have a few errors still im also not sure how to add the contents of the 2 arrays together when i have filled them

    the whole point of this program is to stop overflow errors if that helps
    Last edited by c_beginner; 08-04-2004 at 05:17 PM.

  4. #4
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    You should use code tags when you are posting code - it makes it nicer to read.

    Read this for an explanation of code tags and how to use them.

    As to your code:
    Code:
    #include <stdio.h>
    
    main ()
    {
    
    int *inf_ptr;
    int array1[20];
    int array2[20];
    int array3[20];
    int i;
    
    
    infptr = fopen("mydata.txt", "r");  // Missing an underscore in this one
    
    
    if (infptr==NULL)
    {
    printf(" cannot open file for reading");
    }
    else
    {
    for (i=0; i<20; i++)
    {
    if (fptr == " ") // did you define this anywhere in your code?
    break;
    
    fscanf(fptr,"%d", array1[i]);
    }
    {
    for (i=0; i<20; i++)
    {
    if ( fptr == " ")
    break;
    
    fscanf(fptr,"%d", array2[i]);
    }
    }
    
    return 0;
    }
    You need to double check your variable names and also have a look at your brackets - be sure you don't have too many, or not enough - mismatched parentheses can cause problems. Get these problems cleaned up, and post your code again.

    ~/
    Last edited by kermit; 08-04-2004 at 06:06 PM.

  5. #5
    Registered User
    Join Date
    Aug 2004
    Posts
    3
    have gone through and corrected the grammar but am still having the same problems:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main ()
    
    {
    	int *inf_ptr;
    	int array1[20];
    	int array2[20];
        int array3[20];
    	int i;
    	
    
    	inf_ptr = fopen("mydata.txt", "r");
    	if (infptr==NULL)
    	{ 
    	printf("cannot open file for reading");
    	} 
    else
    	{	  	
      for (i=0; i<20; i++)
     
        if (fptr == " ")
            break;
            
        fscanf(fptr,"%d", array1[i]);
     
      for (i=0; i<20; i++)
     
        if (fptr == " ")
            break;
            
        fscanf(fptr,"%d", array2[i]);
    	}	
    		
    	return 0;
    }
    Last edited by c_beginner; 08-05-2004 at 05:06 AM.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    have gone through and corrected the grammar but am still having the same problems:
    Specificly, you seem to be having problems using [code] tags, and the "Preview" button...

    On an aside, don't you pay attention to anything? Seriously. LOOK at your compiler warnings, that's what they're there for:
    Code:
    warn.c: In function `main':
    warn.c:15: warning: assignment from incompatible pointer type
    warn.c:16: `infptr' undeclared (first use in this function)
    warn.c:16: (Each undeclared identifier is reported only once
    warn.c:16: for each function it appears in.)
    warn.c:24: `fptr' undeclared (first use in this function)
    warn.c:27: warning: format argument is not a pointer (arg 3)
    warn.c:34: warning: format argument is not a pointer (arg 3)
    warn.c:11: warning: unused variable `array3'
    Pay attention, or just give up programming, because it's not for those who ignore warnings. fopen retrurns a FILE *, and not a pointer to an integer. Furthermore, you don't compare the pointer itself to a space. Even if you did, you can't compare strings, (" " that way. And even if you could compare a single character to said pointer, you'd have to dereference said pointer to compar it to a single character.

    I'd suggest buying a C book, or paying attention in whatever class you're taking, because you have no grasp for the basics.

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Mar 2004
    Posts
    536
    I think this is actually a pretty interesting project, but probably a bit too much for someone "just starting to learn the language." Rather than give up programming, maybe you can discipline yourself to learn some fundamentals before attacking some really interesting problems.

    I can see a progression of smaller programs, each one builds on the previous step.

    If I understand your intention, I see two main tasks (you can do either one first, then do the other, then combine into your program).

    1. Reading text characters into arrays.

    2. Adding the two numbers whose digits are represented in arrays. (It was previously pointed out that you can't expect to add 20-digit decimal numbers using any commonly available C-compiler.)


    These can be two separate programs. The final step is to get the information that you got in step1 into whatever form that you need for step 2.


    Task 1 can be further broken down into sub-tasks. Make sure you have a program that operates properly before you go to the next step.

    a. Read a sequence of ASCII characters into an array.
    (Check for valid input: must be a decimal digit, must have 20 or fewer characters). Print out exactly what you entered into the array elements.

    b. Read two such sequences into two arrays on an input line. (Check for valid input: must be two sequences of decimal digits, the two sequences separated by whitespace.)

    c. Read as many input lines as there are in the file.

    Task 2 (start with a separate program):
    Define two arrays for the addend and augend. For purposes of this task, simply initialize them in the program to some numbers that you want to use as an example. You may want to have another array to hold the sum. (Remember that if the input numbers may have as many as 20 digits each, the output number may have 21 digits.)

    How do you add decimal numbers on paper: align the numbers so that their least significant digits are above each other. Then:

    Add the two least significant digits. If the sum is greater that 9, put 0 in the least significant digit of the sum, and set a "carry" value to 1. If the sum is less than or equal to 9, put this value in the least significant digit of the sum and set the "carry" value to 0.

    Repeat for the remaining digits: add the next digits and the carry value from the previous step. If this sum is greater than 9, put 0 into this position of the sum, and set the "carry" value to 1 for the next step. etc. etc.

    While your are debugging your program, you probably will want to print out the results (sum digit and carry digit) at each step.

    Finally, see how you can get input information (assuming the operands can have from 1 to 20 digits) into the form that you used in the addition routine. Task 2 can be implemented as a function that is integrated into the main program and is called after each input line is read (and validated).

    Is this enough to get you started?

    Good luck!

    Dave

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with loading files into rich text box
    By blueparukia in forum C# Programming
    Replies: 3
    Last Post: 10-19-2007, 12:59 AM
  2. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  3. Reading binary files and writing as text
    By thenrkst in forum C++ Programming
    Replies: 8
    Last Post: 03-13-2003, 10:47 PM
  4. Reading spaces, carrage returns, eof from text files
    By thenrkst in forum C++ Programming
    Replies: 1
    Last Post: 03-11-2003, 05:18 AM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM