給定這樣的問題:從整數串列中找到最小值和最大值。有 T 個測驗用例,對于每個測驗,列印編號。當前的測驗用例和答案。
輸入.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
請幫我修復我的代碼。提前感謝您的答案。
uj5u.com熱心網友回復:
在 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一個可以在一次通過中同時獲得最小值和最大值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437525.html
上一篇:如何使用<imgsrc>或<ahref>標簽驗證影像在前端是否可見/存在
下一篇:點擊多個:真柏
