Retrieving an integer from a .txt file

Ok so I'm trying to retrieve an integer from the file reference1.txt but every time it keeps failing to retrieve it and outputting -858993460. The rest of the code functions great, it's just this part which doesn't seem to work. Any help?

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
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <string>
using namespace std;



int main() {
	ifstream myfile;
	myfile.open("C:\\reference1.txt");
int num;
	for (int i = 0; i < 1; i++) {
	myfile >> num;
	}
	myfile.close();
	cout << num << '\n';
	int K;
	cin >> K;
	int a;
	if (num<K){
		a=2;
	}else{
		if (num>K){
			a=0;
		}else{
			a=1;
		}
	}
	ofstream myfile2;
	myfile2.open("C:\\reference2.txt");
	myfile2 << a;
	myfile2.close();

	system("Pause");
		return 0;
}
Hi,

1
2
3
for (int i = 0; i < 1; i++) {
	myfile >> num;
	}


The above code would be better of reading a file by not using a for loop, and instead reading a file until there is something in the file, for example:

1
2
3
4
5
6
string input;
while (!myfile.eof())
{
      getline(myfile, input);
}
myfile.close()

I've tried that and something like it before but it doesn't seem to allow me to retrieve integers for use later on, hence why I switched to the for loop.
In your code above 'num' is not declared so input from the file does not exist:

try to input from the file into string and then convert string to number by using atoi() function

1
2
3
4
int num;
myfile.open(/*file_name.txt*/);
myfile >> num;
myfile.close();

Last edited on
I don't know how but what seems to be my original code I posted decided to work today

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
30
31
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <string>
using namespace std;



int main() {
	ifstream myfile;
	myfile.open("C:\\reference1.txt");
	int num;
	for (int i = 0; i < 1; i++) {
	myfile >> num;
	}
	myfile.close();
	cout << num << '\n';
	int K;
	cout << "Enter desired value";
	cin >> K;
	int a;
	if (num<K){
		a=2;
	}else{
		if (num>K){
			a=0;
		}else{
			a=1;
		}
	}
	ofstream myfile2;
	myfile2.open("C:\\reference2.txt");
	myfile2 << a;
	myfile2.close();

	system("Pause");
		return 0;
}
Topic archived. No new replies allowed.