Given problem like this: Find the min and max from a list of integers. There are T test cases, for each test, print no. of current test cases and the answer.
Input.txt file
3
3 4 5 1 2
100 22 3 500 60
18 1000 77 10 300
Output
Test case 1: Max :5, Min :1
Test case 2: Max :500, Min :3
Test case 3: Max :1000, Min :10
In C , how can I process only one line from standard input in each test case iteration. The code that I have tried is like this.
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main() {
freopen("input.txt","r",stdin);
int T;
cin>>T;
for(int i=1; i<=T; i) {
vector<int> arrayInt;
int n;
//Should only process one line for each test case
while(cin>>n) {
arrayInt.push_back(n);
}
int max = *max_element(arrayInt.begin(), arrayInt.end());
int min = *min_element(arrayInt.begin(), arrayInt.end());
cout<<"Test case " << i << ": Max :" << max << ", Min :"<< min << "\n";
}
}
Output that I got when I run it on the command line
Test case 1: Max :1000, Min :1
Please help me to fix my code. Thanks in advance for the answers.
CodePudding user response:
In C , how can I process only one line from standard input in each test case iteration.
std::getline
reads until it finds a line break (thats the default, other delmiters can be used).
Replace
while(cin>>n) {
arrayInt.push_back(n);
}
With
std::string line;
std::getline(std::cin, line);
std::istringstream linestream{line};
while(linestream >> n) {
arrayInt.push_back(n);
}
Also note that there is std::minmax_element
which can get both min and max in a single pass.