pointer


hello, i need to find the least number in the file by a pointer. If the least number in the beginning of the file the program does not find it. Write your tips please.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
using namespace std;
int g,d,*s,*a,*j,*k,*o;
int main()
{
  ifstream f("ugiai.txt");
  f>>d;
  a=&d;
while (!f.eof())
   {
    f>>g;
    s=new int;
    s=&g;
    if(*s<*a)
        {
        j=new int;
        *j=*s;
        delete s;
        o=new int;
        o=&g;
        }
    if(*o<*a)*a=*o;
  }
  if (*a<*j)cout<<"the least: "<<*a;
       else cout<<"the least: "<<*j;
  delete o;
  delete j;
}
Last edited on
Hi,

Write your tips please.

Put your code between code tags so it will have indentation and will look nice: [code ] insert it here [/code]
Do not use global variables.
Check if the file opened successfully. like if ( !f ) { /* handle error */ }
Do not loop on eof(). use while( f >> var ) { } instead
Use more meaningful variable names
Do you really need to use new ?

1
2
s=new int;
s=&g;

Uhmm, By doing this you lose the address of the newly allocated integer and will have memory leak and
crash later because of delete s;. Do you meant s = new int( g ) instead ?

Can you post the instructions so we can evaluate it further ?
Last edited on
thanks for advise, instruction: find the least number in the file by using pointer only.
As a suggestion, if you really want to use pointers and dynamic memory only,
you can simply use 2 pointers to dynamic storage, like :
1
2
int* least = new int;
int* current = new int;


then do the comparison as usual. something like :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream f( "ugiai.txt" );
    if( !f ) { // if stream is bad
        cout << "Error in opening file. exiting...\n";
        return 1;
    }

    int* least = new int;
    int* current = new int;

    if( f >> *least ) { // if reading of first number succeeds
        while( f >> *current ) {  // read the rest (breaks if bad input is encountered)
            if( /*  *current is less than *least */ )  
                // then change *least to *current
        }
    }

    cout << "Least number : " << *least << '\n';

    delete least;
    delete current;
}
Last edited on
Topic archived. No new replies allowed.