Using pointers to move to the next integer in a file

Hello everyone, I'm fairy new to pointers. I'm looking to use p++ in order to move to the next integer within a file. When p++ is used, the program returns a garbage value. Appreciate any insight.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using namespace std;

int main() {
	fstream file1("text1.txt", std::ifstream::in);

	int* p;
	int num;

	if (file1.good())  // note 1
	{
		file1 >> num >> ws;
		p=&num;
		p+=2; // returns garbage
		cout << *p;
	}
	return 0;
}
Pointer arithmetics. When you do p+=2 the pointer then points to whatever is stored two memory addresses from that of num.

Aceix.
Last edited on
You can use stream iterators for that:
1
2
3
4
5
6
7
std::ifstream file1("text1.txt");
std::istream_iterator<int> p(file1);
std::istream_iterator<int> end;
while(p != end) {
    std::cout << *p;
    ++p;
}
Holy cow, MiiNiPaa you're a lifesaver. I've honestly have been working on trying to do this for about 4 days now with about 40 hours clocked in... I couldn't move on with life without being able to solve this. I got lots of beef asking too much at stackoverflow but this forum is such a blessing.

Thanks again MiiNiPaa, and have a great day!

Best,
decoy98
Topic archived. No new replies allowed.