fstream

Hello guys i need help reading from a file.
i'm saving integers and want to read as integers.
for example:
1 2 3
4 5 6

This the way integers are saved but i want to read each one by it self as i saved them. if there's a simple way to do it please tell me if not just explain how it's done. thank you
> i want to read each one by it self as i saved them
don't understand what you mean
1
2
3
4
5
std::ifstream input("filename");
int n;
while(input >> n){
   //...
}
that would process the numbers one by one
Hello charbel542,

I will expand on what ne555 has said which works.

I like to use this:
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
38
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
#include <chrono>
#include <thread>

#include <fstream>

int main()
{

	const std::string inFileName{ "" }; // <--- Put file name here.

	std::ifstream inFile(inFileName); // <--- No quotes.

	if (!inFile)
	{
		std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(5));  // <--- Needs header files chrono" and "thread". Optional as is the header files.
		return 1;  //exit(1);  // If not in "main".
	}

	int n;

	while (inFile >> n)
	{
		//...
	}

	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
        // Just put a comment on the line if you do not need it for now.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;
}

One main concept here is the if statement. It is always a good idea to check that an input file is open before you try to use it. Otherwise the program would continue without being able to read the file. And the while loop condition would be false passing be the loop to what is next.

Line 20 is something I use to keep the console window open long enough to read the message before the "return" closes the window.

The while condition works based on there being something to read. When you reach end of file and the "eof" bit is set the condition will fail and you will continue with what comes after the while loop. This is generally the best way to read a file of unknown length.

Hope that helps,

Andy
Topic archived. No new replies allowed.