Reading a Value from a Text File

Hello:

I would like to know how to read a value (for example, 7.050) from the text file:

C:\test\FreqData.txt

and assign the value from the file to the variable:

float Freq

Thanks in advance.

Brian

Use either forward slash '/' or double backslash '\\' as separator in file name.
1
2
3
4
std::ifstream fin("C:\\test\\FreqData.txt");

float Freq;
fin >> Freq;
It depends on the format of the file as to how simple or complex the code will be. At the most basic, a file containing 7.0501 (had to make it different a littel) you would do something like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <iostream>

int main()
{
	std::ifstream inFile("FreqData.txt");
	if(!inFile) std::cout << "Failed to load file\n";
	
	float Freq;
	
	inFile >> Freq;
	
	std::cout << Freq << '\n';
	
	inFile.close();
	
	return 0;
}
7.0501

A file of numbers, that may need summed up or worked on?
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
#include <fstream>
#include <iostream>
#include <vector>

int main()
{
	std::ifstream inFile("FreqData.txt");
	if(!inFile) std::cout << "Failed to load file\n";
	
	float Freq;
	std::vector<float> fileData;
	
	while (inFile >> Freq){
		if(Freq >= 0) fileData.push_back(Freq);  // remove any negative numbers and add to vector
	}
	
	// std::cout << Freq << '\n';
	for (auto c : fileData){
		std::cout << c << ' ';
	}
	
	std::cout << std::endl;
	
	return 0;
}
7.0501 7.4332 0.021 2.333 112.3 112 34 3344.21 334.2 345.338 344.2 988.9

File:

7.0501 7.4332
0.021 2.333
-1223.3
112.3 112.0
34.0 3344.21 334.2 345.3382 344.2 988.9

You can basically make the file however you want, just remember that as the programmer it falls on you to code it so the program can read it without any problem.
Last edited on
Make sure to check for eof(), otherwise you'll read the last value twice.
Last edited on
BHX's code has that error.
Use the reading operation instead while(inFile >> Freq)
My code has that error because it originally looked like ne555's recommendation of while(inFile >> Freq) and didn't have an eof() check. It was a last minute change that came about from viewing beginner forums on other sites where beginners were confused by while(cin >> var). After some debating I opted to move it, but forgot to add an eof() check. Wanted to avoid the risk of confusion, which led me to delete another example I wrote due to thinking it may have been too much for what this topic had asked.

closed account (48T7M4Gy)
http://stackoverflow.com/questions/5837639/eof-bad-practice
Topic archived. No new replies allowed.