从标准输入逐行处理



给定这样的问题:从整数列表中查找最小值和最大值。有T个测试用例,对于每个测试,打印当前测试用例的编号和答案。

Input.txt文件

3
3 4 5 1 2
100 22 3 500 60
18 1000 77 10 300

输出

Test case 1: Max :5, Min :1
Test case 2: Max :500, Min :3
Test case 3: Max :1000, Min :10

在C++中,如何在每次测试用例迭代中只处理来自标准输入的一行。我尝试过的代码是这样的。

#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";
}
}

当我在命令行上运行它时得到的输出

Test case 1: Max :1000, Min :1

请帮我修复代码。提前感谢您的回答。

在C++中,如何在每次测试用例迭代中只处理标准输入的一行。

std::getline读取,直到找到换行符(默认情况下,可以使用其他三角形(。

更换

while(cin>>n) {
arrayInt.push_back(n);
}

std::string line;
std::getline(std::cin, line);
std::istringstream linestream{line};       
while(linestream >> n) {
arrayInt.push_back(n);
}

还要注意,有一个std::minmax_element,它可以在一次通过中获得最小值和最大值

最新更新