如何计算由空格分隔的文本文件中的输入整数/数字。我需要知道用户通过文件而不是从控制台输入了多少个数字。
这就是我所做的。但它会计算所有数字。
// 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
答案 0 :(得分:2)
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++;
}
答案 1 :(得分:1)
您可以在一行中计算文件中存在的数字。
你在这里。
#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>() );