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?
#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.
#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';
}