对于 C++ 中给定数量的测试用例,如何从标准输入读取数据
How to read data from stdin, for a given number of test cases in C++
这听起来可能很傻,但这是我第一次在线解决编程竞赛。问题通常描述为:
Input:
First line indicates the number of test cases t.For the next 't' lines the data is entered.
我编写了以下程序(包括正确的 headers):
vector<string> read_strings(int t_cases) {
vector<string> ip_vec;
string line, str;
int cnt = 0;
while (cnt != t_cases-1) {
std::getline(std::cin, line);
++cnt;
}
std::istringstream iss(line);
while (iss >> str) {
ip_vec.push_back(str);
}
return ip_vec;
}
但是这个程序总是卡在输入循环中。我还尝试通过将 iss
放在第一个 while
循环中来解析该行。如果有人能为我提供有关如何解决此问题的指示,我将能够最终测试程序的其余部分。
谢谢。
您需要在读取时将行添加到矢量中。第一个 while 循环读取所有测试用例,但没有将它们保存在某个地方。然后下一个 while 循环尝试读取 line
,这是读取的最后一个测试用例。尝试以下操作:
vector<string> ip_vec;
string line, str;
for (int cnt = 0; cnt < t_cases; cnt++) {
std::getline(std::cin, line);
ip_vec.push_back(line);
}
既然您开始学习编程竞赛的运作方式,我不建议您存储所有给定的输入。通常,您可以存储输入的数量 t 并且对于每个测试用例,程序在读取下一个测试之前输出该测试的答案案件。例如:
for (int i = 1; i <= t; i++) {
cin >> input;
// Some computations specific to the problem
cout << output << endl; // Pay attention on how the problem wants the output to be printed.
}
如果问题没有给你测试用例的数量,你可以简单地将循环更改为:
while (cin >> input) {
// Computations...
cout << output << endl;
}
这通常是我解决编程竞赛问题的方式。
编辑:正如@AnkitKulshrestha 所指出的,如果每个测试用例必须读取不止一个输入,您可以像这样简单地读取它们(例如,三个输入):
while (cin >> a >> b >> c) {
// Computations...
cout << output << endl;
}
这听起来可能很傻,但这是我第一次在线解决编程竞赛。问题通常描述为:
Input:
First line indicates the number of test cases t.For the next 't' lines the data is entered.
我编写了以下程序(包括正确的 headers):
vector<string> read_strings(int t_cases) {
vector<string> ip_vec;
string line, str;
int cnt = 0;
while (cnt != t_cases-1) {
std::getline(std::cin, line);
++cnt;
}
std::istringstream iss(line);
while (iss >> str) {
ip_vec.push_back(str);
}
return ip_vec;
}
但是这个程序总是卡在输入循环中。我还尝试通过将 iss
放在第一个 while
循环中来解析该行。如果有人能为我提供有关如何解决此问题的指示,我将能够最终测试程序的其余部分。
谢谢。
您需要在读取时将行添加到矢量中。第一个 while 循环读取所有测试用例,但没有将它们保存在某个地方。然后下一个 while 循环尝试读取 line
,这是读取的最后一个测试用例。尝试以下操作:
vector<string> ip_vec;
string line, str;
for (int cnt = 0; cnt < t_cases; cnt++) {
std::getline(std::cin, line);
ip_vec.push_back(line);
}
既然您开始学习编程竞赛的运作方式,我不建议您存储所有给定的输入。通常,您可以存储输入的数量 t 并且对于每个测试用例,程序在读取下一个测试之前输出该测试的答案案件。例如:
for (int i = 1; i <= t; i++) {
cin >> input;
// Some computations specific to the problem
cout << output << endl; // Pay attention on how the problem wants the output to be printed.
}
如果问题没有给你测试用例的数量,你可以简单地将循环更改为:
while (cin >> input) {
// Computations...
cout << output << endl;
}
这通常是我解决编程竞赛问题的方式。
编辑:正如@AnkitKulshrestha 所指出的,如果每个测试用例必须读取不止一个输入,您可以像这样简单地读取它们(例如,三个输入):
while (cin >> a >> b >> c) {
// Computations...
cout << output << endl;
}