Get Size of Array from text file

If I have a text file is "text.txt" contains: 1 2 3 4
How can I get 4 which is the size of array on text file?
In other words,How can I get the number of the numbers stored in that textfile?
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream myfile;
    myfile.open("text.txt");
    system("pause");
}
Last edited on
The size should be the first number, not the last. Reading the first number in the file is trivial, reading the last number is not so much.
This will read the last number and then read the numbers using a loop based upon the last number.

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
#include <fstream>
#include <iostream>
#include <cctype>

int main()
{
	std::ifstream ifs("text.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open file\n"), 1;

	int pos = 0;

	do {
		ifs.seekg(--pos, std::ios_base::end);

	} while (std::isspace(ifs.peek()));

	while (std::isdigit(ifs.peek()))
		ifs.seekg(--pos, std::ios_base::end);

	int num {};

	ifs >> num;
	ifs.seekg(0, std::ios_base::beg);

        std::cout << "Size is " << num << '\n';

	for (int i = 0; i < num; ++i) {
		int data {};

		ifs >> data;
		std::cout << data << '\n';
	}
}


Why do you need to know the number of numbers? If you want to read the numbers (eg to sum/average etc), then just read and process them.

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

int main()
{
	std::ifstream ifs("text.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open file\n"), 1;

	int num {};
	int sum {};
	int cnt {};

	while (ifs >> num) {
		sum += num;
		++cnt;
	}

	std::cout << cnt << " Numbers were read\n";
	std::cout << "The sum is " << sum << '\n';
}

How can I get the number of the numbers stored in that textfile?

Read the file twice, store the size in a separate file or best use a STL <vector>
Topic archived. No new replies allowed.