C++ Read From File to Array and Compare

  1. #ane

    c_beginner is offline

    Registered User


    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 volition read integers from a text file then concur the values into arrays and finaly add together them together, the numbers in the text file volition exist 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 meridian line would be read into the start assortment then the 2d ready afterward the infinite would be read in to the the second assortment then the values would be added together in a third array and printed on the screen, this procedure would then showtime over again on the second set up of numbers and exercise the same untill there arnt any more than numbers in the text file,

    then far i have made a loop that volition read the kickoff fix of numbers into the kickoff array:

    ( i=0; i<twenty; i++)
    {
    if ( i == " ")
    pause;
    }
    this should read the first numbers in and terminate when it reaches 20 digits or the infinite, simply thats equally far equally i accept got, i dont know if this will really piece of work and am not sure how to make a loop to read the second set up of numbers and then how to get them to add together 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 take so far:
    #include <stdio.h>

    main ()
    {

    int *inf_ptr;
    int array1[twenty];
    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

    itsme86 is offline

    Gawking at stupidity


    There's a couple of fundamental flaws here. The type int is mostly 32 $.25 wide meaning it can only hold numbers up to two^32 (2^31 if information technology's a signed int). An int isn't always 32 bits broad. Information technology'south non actually guaranteed to be anything (except for in relation to other types). Common sizes in employ today are 16 bits, 32 $.25, and 64 bits. Anyway, your compiler is probably using 32-chip ints. A 20 digit number is far larger than this. This is what is referred to equally an "overflow". So that's ane thing yous're going to desire to go along in mind and check when writing this matter.

    I'thousand also not quite sure about adding together ii 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:

    $ true cat foo.c #include <stdio.h> #include <cord.h> #include <stdlib.h>  int chief(void) {   FILE *fp;   int array1[2];   int array2[ii];   char buf[128];    fp = fopen("mydata.txt", "r");   if(fp == Naught)   {     puts("Cannot open file for reading");     exit(EXIT_FAILURE);   }    fgets(buf, sizeof(buf), fp);   sscanf(buf, "%d %d", &array1[0], &array1[one]);   fgets(buf, sizeof(buf), fp);   sscanf(buf, "%d %d", &array2[0], &array2[i]);    fclose(fp);    printf("Set 1 - 1st: %d, 2d: %d\due north", array1[0], array1[one]);   printf("Fix 2 - 1st: %d, 2nd: %d\n", array2[0], array2[ane]);    render 0; }
    Hither's the contents of mydata.txt:
    And here'due south 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 exist happy to answer them.


  3. #iii

    c_beginner is offline

    Registered User


    thanks for replying, since i posted i did a bot more than work on it, but i seem to using a different method than you lot this is what i take:
    #include <stdio.h>

    primary ()
    {

    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 == " ")
    intermission;

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

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

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

    the whole signal of this plan is to finish overflow errors if that helps

    Last edited by c_beginner; 08-04-2004 at 05:17 PM.


  4. #iv

    kermit is offline

    ... kermit's Avatar


    You should use code tags when you are posting code - information technology makes information technology nicer to read.

    Read this for an caption of code tags and how to apply them.

    Equally to your lawmaking:

    Code:

    #include <stdio.h>  primary () {  int                                                      *inf_ptr;                                                int array1[20]; int array2[20]; int array3[20]; int i;                                                  infptr                                                = fopen("mydata.txt", "r");                                                                              // Missing an underscore in this i                                                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 == " ") suspension;  fscanf(fptr,"%d", array2[i]); } }  return 0; }
    You lot need to double check your variable names and also accept a wait at your brackets - be sure you don't have as well many, or non plenty - mismatched parentheses can crusade problems. Get these problems cleaned upwardly, and post your code again.

    ~/

    Concluding edited by kermit; 08-04-2004 at 06:06 PM.


  5. #5

    c_beginner is offline

    Registered User


    accept gone through and corrected the grammar simply am however having the same issues:

    Lawmaking:

    #include <stdio.h> #include <string.h> #include <stdlib.h>  int master ()  { 	int *inf_ptr; 	int array1[xx]; 	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. #half-dozen

    quzah is offline

    ATH0 quzah's Avatar


    have gone through and corrected the grammar but am however having the same issues:

    Specificly, you seem to be having bug using [code] tags, and the "Preview" button...

    On an bated, don't you pay attending to anything? Seriously. Wait at your compiler warnings, that'southward what they're there for:

    Code:

    warn.c: In function `main':                        warn.c:15: alarm: assignment from incompatible pointer type                        warn.c:16: `infptr' undeclared (start use in this function) warn.c:xvi: (Each undeclared identifier is reported only once warn.c:16: for each function it appears in.) warn.c:24: `fptr' undeclared (kickoff apply in this function) warn.c:27: warning: format statement is not a pointer (arg iii) warn.c:34: warning: format argument is not a pointer (arg three) warn.c:11: warning: unused variable `array3'
    Pay attention, or only give upwards programming, because it'due south 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 lot did, you can't compare strings, (" " that mode. And even if you could compare a single character to said arrow, you'd have to dereference said pointer to compar it to a single character.

    I'd suggest ownership a C volume, or paying attending in whatever class yous're taking, because you have no grasp for the basics.

    Quzah.

    Hope is the outset step on the route to disappointment.


  7. #7

    Dave Evans is offline

    Registered User


    I recall this is actually a pretty interesting project, but probably a bit too much for someone "just starting to learn the linguistic communication." Rather than give up programming, perhaps you can discipline yourself to learn some fundamentals earlier attacking some actually interesting bug.

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

    If I understand your intention, I see 2 main tasks (you can do either one get-go, then do the other, so combine into your program).

    1. Reading text characters into arrays.

    ii. Calculation 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 tin can be two separate programs. The terminal step is to get the data that you lot got in step1 into any grade that you need for footstep 2.

    Task one can exist further broken down into sub-tasks. Make certain you accept a programme that operates properly earlier yous go to the side by side stride.

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

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

    c. Read as many input lines as in that location are in the file.

    Task 2 (start with a separate program):
    Ascertain two arrays for the addend and augend. For purposes of this task, simply initialize them in the program to some numbers that you desire to use as an example. You may want to have some other 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: marshal the numbers and then that their to the lowest degree significant digits are to a higher place each other. And so:

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

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

    While your are debugging your program, y'all probably will desire to print out the results (sum digit and conduct digit) at each step.

    Finally, come across how you can go input information (assuming the operands can have from 1 to 20 digits) into the grade that you used in the improver routine. Task 2 can be implemented equally a function that is integrated into the main plan and is called after each input line is read (and validated).

    Is this plenty to get yous started?

    Expert luck!

    Dave


barneslonts1937.blogspot.com

Source: https://cboard.cprogramming.com/c-programming/55444-reading-integers-into-arrays-text-files.html

0 Response to "C++ Read From File to Array and Compare"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel