ifstream read last line enter ! how prevent

Write your question here.

1
2
3
4
5
6
7
8
  //txt data
40
30
20
2
4
5
  // <---this empty enter data 


1
2
3
4
5
void readText( ifstream &infile ){
      while ( !inFile.eof() ){
            inFile >> data;
      }
}


but when display output
1
2
3
4
5
6
7
40
30
20
2
4
5
-81828273 // This is the enter empty data 

how to ignore it?
1
2
3
4
5
void readText( ifstream &infile ) {
    while(infile >> data) {
        //...
    }
}


Also your question is not really clear.
We are still human being, we'd like if we get better questioning.

"Write your question here" can be deleted from your post.
here is my function
1
2
3
4
5
6
7
8
9
10
11
12
13
void bstree::readTextFile( ifstream &inFile , nodeptr &root ){
	node *leaf;
	while( inFile >> leaf->element ){
		leaf = new node;
		inFile >> leaf->element;
		leaf->height = 0;
		leaf->left = leaf->right = NULL;
		
		if( root == NULL )
			root = leaf;
		insert( leaf->element , root );
	}
}


u mean i should change to this?
1
2
3
4
5
6
7
8
9
10
11
12
13
void bstree::readTextFile( ifstream &inFile , nodeptr &root ){
	node *leaf;
	while( inFile >> leaf->element ){
		leaf = new node; <-- // leaf is every new node
		//inFile >> leaf->element;
		leaf->height = 0;
		leaf->left = leaf->right = NULL;
		
		if( root == NULL )
			root = leaf;
		insert( leaf->element , root );
	}
}

but how do i let leaf = new node run?
where should i move it
THis is an error:
1
2
	node *leaf;
	while( inFile >> leaf->element ) {

leaf is an uninitialised pointer. Attempting to access something at that memory location is not valid. Most likely the program will crash.
i know.
but then he told me to change this?
so how should i suppose to change it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void bstree::readTextFile( ifstream &inFile, nodeptr &root) {
    node * leaf = new node;
    while( inFile >> leaf->element ) {
        /* You can now freely handle 'leaf' */
        leaf->height = 0;
        leaf->left = leaf->right = 0;
        if(!root)
            root = leaf;
        insert(leaf->element,root);

        leaf = new node;
    }
    /* Cannot read last leaf, delete unused element */
    delete leaf;
    leaf = 0;
}


This should be able to fully substitute your old way.
Last edited on
it's work . can u tell me why need to delete leaf and set leaf = 0;?
in your last line?
can explain? haha
I've edited my post above and inserted a comment. Just in case I'll explain:

Every time you read a leaf->element (line 3 over), you have a new, empty allocated 'leaf'.

But if you fail to read 'leaf', the "while" loop will fail, and the 'leaf' node is still allocated, even if unused.

This is why you still need to delete leaf, otherwise it will cause a memory leak.
Topic archived. No new replies allowed.