0

//ok, thanks for help. i edited the code, passed a pointer and now the it prints the number from particular row, prints the number of that row, and prints the sum off all consiquent numbers. Good so far, but... What i want do do next, is to assign each of the sums to an array, so i can use for loop to check whether the resulting sum equals to any previous resulting sums. i use tab[n]==result; unfortunatelly after the while loop is done, all the array elements are empty...thanks//

include

include

int main()
{
    int result =0;

    read_ints("numbers.txt", &result);


}



void read_ints (const char* file_name, int *result)
{

  FILE* file = fopen ("numbers.txt", "r");
  int i = 0;
  int n=1; //row number//
  int tab[n]; //array

  if (file == NULL)
  {
   printf("unable to open file %s", file_name);

  }
  fscanf (file, "%d", &i);
  while (!feof (file))
    {
      printf ("%d ", i);
      *result += i;
      tab[n]==result;
      printf("row number: %d \n", n);
      n++;

      printf("\n sum of this number and all numbers before is: %d\n", *result);

      fscanf (file, "%d", &i);

    }
          printf("\nnumber from row number one is ... : %d\n", tab[1]);
  fclose (file);



}
  • 2
    The function takes 2 arguments but you pass 0. – 001 Jan 04 '19 at 21:21
  • Did you see any warnings from the compiler? – Eugene Sh. Jan 04 '19 at 21:23
  • no warnings from compiler –  Jan 04 '19 at 21:27
  • 2
    Then throw it away. Your function has no prototype before called. And is called with wrong arguments number. If the compiler is not warning about it, it is garbage, or you have explicitly disabled the warnings. – Eugene Sh. Jan 04 '19 at 21:34
  • Note that you often have to turn on warnings when you compile. For example with gdb, you would compile with the `-Wall` compiler flag to get most warning messages turned on. – bruceg Jan 04 '19 at 21:38
  • 1
    @bruceg With `gcc` I guess... – Eugene Sh. Jan 04 '19 at 21:48
  • @EugeneSh. haha... oops. Too late to edit. – bruceg Jan 04 '19 at 21:50
  • the posted code does not compile. When compiling, enable the warnings, then fix those warnings. ( for `gcc`, at a minimum use: `-Wall -Wextra -pedantic -Wconversion -std=gnu11` ) Note: other compilers use different options to perform the same functionality. – user3629249 Jan 04 '19 at 23:45
  • @bruceg, `-Wall` is NOT how to get the most info from `gdb` Rather use the option: `-ggdb3` in both the compile and the link steps. And if you actually meant `gcc`, the option: `-Wall` is just the beginning of what is needed, see my prior comment – user3629249 Jan 04 '19 at 23:47
  • NEVER use `while (!feof (file))` It does not do what you are expecting. suggest: `while( fscanf (file, "%d", &i); == 1 )` and remove the call to `fscanf()` from the end of the loop – user3629249 Jan 04 '19 at 23:57
  • regarding: `result=result+i;` a local variable defined in a different function is invisible in a different function. I.E. the local variable 'goes out of scope' – user3629249 Jan 04 '19 at 23:59
  • for ease of readability and understanding: please consistently indent the code. Indent after every opening brace "{". Uningent before every closing brace "}". Suggest each indent level be 4 spaces – user3629249 Jan 05 '19 at 01:33
  • regarding: `#include ` It is a poor programming practice t include header files those contents are not being used. – user3629249 Jan 05 '19 at 01:39
  • i made some improvements, but now another problem –  Jan 06 '19 at 20:24
  • regarding; `int n=1; //row number// int tab[n]; //array` and ` tab[n]==result; .... n++;` the declaration of `tab[]` is only declaring a single entry in that table. As soon as you try to assign a value past `tab[0]` the code is writing to memory past the end of the table. This is undefined behavior and can result in a seg fault event. BTW: in C, an index into an array is in the range 0...(number of elements in array -1) – user3629249 Jan 07 '19 at 04:05
  • regarding: `printf("\nnumber from row number one is ... : %d\n", tab[1]);` since the variable `tab[]` only has single element and the first element in an array is index 0, so this print statement is trying to read memory past the end of the table. – user3629249 Jan 07 '19 at 04:08
  • please do NOT modify the posted code. Rather add a `EDIT` showing the revised code as a separate block – user3629249 Jan 07 '19 at 04:11

3 Answers3

1

Your code is mostly right. You're just calling read_ints incorrectly. You should pass in a pointer to result if you want a value returned.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void read_ints (const char* file_name, int *result) {
    FILE* file = fopen (file_name, "r");
    int i = 0;

    if (file == NULL) {
        printf("unable to open file %s\n", file_name);
        return;
    }

    fscanf (file, "%d", &i);
    while (!feof (file))
    {
        printf ("%d ", i);
        *result += i;
        printf("\n suma tej liczby ze wszystkimi poprzednimi wynosi: %d\n", *result);
        fscanf (file, "%d", &i);

    }
    fclose (file);
}

int main() {
    int result =0;

    read_ints("liczby.txt", &result);

}
bruceg
  • 2,433
  • 1
  • 22
  • 29
  • 4
    It is actually mostly wrong. There is no error checking when opening file, the [`while (!feof (file))` is wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) as well - – Eugene Sh. Jan 04 '19 at 21:49
  • @EugeneSh. For his single threaded class assignment, maybe it will be ok. But, definitely checking file for NULL is always a good idea. I will update my answer. – bruceg Jan 04 '19 at 21:52
  • 2
    The only thing that saves you here is that `fscanf` is at the end of the [**while ( !feof (file) ) is always wrong?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) loop so that the value of `i` isn't used between the `fscanf` call and the `feof` check. It's wrong, but by happy chance, no *Undefined Behavior* is invoked. – David C. Rankin Jan 05 '19 at 01:36
0

the following proposed code:

  1. properly checks for errors
  2. properly passes the error text to stderr, including the text reason the system thinks the error occurred.
  3. uses the returned value from fscanf() to control the loop
  4. properly contains a 'prototype' for the sub function
  5. properly uses void inside the parens of main() and the prototype of the sub function that receives no parameters.
  6. consistently indents the code, for readability
  7. cleanly compiles
  8. documents why each header file is included

And now, the proposed code:

#include <stdio.h>   // FILE, perror(), fopen(), printf(), fclose()
#include <stdlib.h>  // exit(), EXIT_FAILURE



void read_ints ( void );


int main( void )
{
    read_ints();
}



void read_ints ()
{
    FILE* file = fopen ("liczby.txt", "r");
    if( !file )
    {
      perror( "fopen to read liczby.txt failed" );
      exit( EXIT_FAILURE );
    }


    int i = 0;
    int result = 0;
    while ( fscanf ( file, "%d", &i) == 1 )
    {
      printf ("%d ", i);
      result=result+i;
      printf("\n suma tej liczby ze wszystkimi poprzednimi wynosi: %d\n", result);
    }
    fclose (file);
}
user3629249
  • 16,402
  • 1
  • 16
  • 17
  • this code actualy does not function properly when compiled. maybe it works for small inputs but for a text file with 1000 rows it counts only 5 consiquent integers –  Jan 06 '19 at 18:40
  • the only reason it would not work is if the file contains other than integers and white space. I.E. if it does not work for you then the input file contains something else, like a comma or semicolon, etc – user3629249 Jan 07 '19 at 03:55
  • does your input file contain 'wide' characters? if so, then the original posted code is trying to work with the wrong kind of characters. Please post the first few lines of the input file. (another reason to post a [mcve] ) – user3629249 Jan 07 '19 at 03:58
0

//ok, the code looks better now, but still, the result values doesnt seem to store in the tab[] array. this is due to lack of a pointer or bad declaration of the array(?).
i intented it to be a dynamic array, so that i dont need to declare the specific size of the array.//

#include <stdio.h>
#include <stdlib.h>
void read_ints(const char* file_name, int *result);

int main()
{
    int result =0;
    read_ints("numbers.txt", &result);
}
void read_ints (const char* file_name, int *result)
{
  FILE* file = fopen ("numbers.txt", "r");
  int i = 0;
  int n=0; //row number//
  int m;
  int tab[m]; //array//
  if (file == NULL)
  {
   printf("unable to open file %s", file_name);
  }
  while ( fscanf (file, "%d", &i) ==1)
    {
       n++;
      printf ("%d\n ", i);
      *result += i;
      printf("\n we are at row nr. %d sum of this number and all numbers before is: %d\n", n, *result);
       tab[n]==*result;
    }
          printf("\nnumber from row number one is ... : %d\n", tab[1]); //this does not work properly //
  fclose (file);
}