Reputation: 13
How do I count the input integers/numbers from a text file that is separated by spaces. I need to know how many numbers does the user inputted via file not from the console.
Here is what I did. But it counts all the numbers instead.
// Counting of Arrival Time //
ifstream arrival_counting;
arrival_counting.open("arrival.in");
if (arrival_counting.fail()) {
cout << "Input file opening failed.\n" << endl;
exit(1);
}
int count_arr = 0;
char next1;
arrival_counting.get(next1);
while(!arrival_counting.eof()) {
if(isdigit(next1)) {
count_arr++;
}
arrival_counting.get(next1);
}
// Counting of Service time //
ifstream service_counting;
service_counting.open("service.in");
if (service_counting.fail()) {
cout << "Input file opening failed.\n" << endl;
exit(1);
}
int count_ser = 0;
char next2;
service_counting.get(next2);
while(!service_counting.eof()) {
if(isdigit(next2)) {
count_ser++;
}
service_counting.get(next2);
}
cout << "ARRIVAL: " << count_arr << endl;
cout << "SERVICE: " << count_ser << endl;
arrival_counting.close();
service_counting.close();
arrival.in
12 31 63 95 99 154 198 221 304 346 411 455 537
service.in
40 32 55 48 18 50 47 18 28 54 40 72 12
Upvotes: 0
Views: 297
Reputation: 311018
You can count the numbers that are present in a file in one line.
Here you are.
#include <iterator>
//..
std::ifstream arrival_counting("arrival.in");
if (arrival_counting.fail()) {
std::cout << "Input file opening failed.\n" << std::endl;
exit(1);
}
auto n = std::distance( std::istream_iterator<int>( arrival_counting ),
std::istream_iterator<int>() );
Upvotes: 1
Reputation: 23058
ifstream arrival_counting("arrival.in");
if (arrival_counting.fail()) {
cout << "Input file opening failed.\n" << endl;
exit(1);
}
int count_arr = 0;
int next1;
while(arrival_counting >> next1) {
count_arr++;
}
Upvotes: 2