输入如下:
2
3 2 1 4
10.3 12.1 2.9 1.9
2 1 3
9.8 2.3 1.2所以2是测试用例的数量。然后有一个空行。然后是一个测试用例。单个测试由两行分别为整数和浮点值的值组成。整数的数量等于浮点值的数量。然后,再次出现一个空行,随后是第二个测试。
我面临着两个问题:第一,如果我知道有多少个数字可以用于循环,第二个问题是在测试用例之后和测试用例之间有空行。我不知道如何使用cin阅读它们或忽略它们。我将把这些值存储在向量中。谢谢
发布于 2013-09-28 03:24:07
您可以使用getline函数读取行,例如:
string line;
std::getline(std::cin, line);然后,您需要解析该行。有两个案例(在阅读了测试案例的数量之后)。要么是空行,要么是n整数。您可以逐个读取整数并将它们添加到您的向量中。如果在缓冲区结束后得到0个整数,那么它就是一个空行:
unsigned int n;
std::ostringstream sin(line);
while (sin >> number)
{
// add number to your vector
++n;
}
if (n == 0)
// go back and try getline again现在有了n,用浮点数读取下一行应该很容易。只需使用循环,因为您知道每个测试用例的浮点数与整数数相同。
发布于 2013-09-28 03:33:35
我认为下面的程序可以做你想要的事情。
#include <iostream>
#include <iterator>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
int main() {
// Identify the number of tests
std::string ntests_str;
std::getline(std::cin, ntests_str);
int ntests = boost::lexical_cast<int>(ntests_str);
// Iterate over all tests
for (int i = 0; i < ntests; i++) {
// Read the integer numbers
std::string integers;
while (integers.empty())
std::getline(std::cin, integers);
// Split the integers into a vector of strings
std::vector<std::string> intstr_vec;
boost::split(intstr_vec, integers, boost::is_any_of(" "));
// Convert to integers
std::vector<int> int_vec;
int_vec.resize(intstr_vec.size());
std::transform(intstr_vec.begin(), intstr_vec.end(), int_vec.begin(),
[&](const std::string& s) {
return boost::lexical_cast<int>(s);
}
);
// Read the floating point numbers
std::string fnumbers;
std::getline(std::cin, fnumbers);
// Split the floating-point numbers into a vector of strings
std::vector<std::string> fstr_vec;
boost::split(fstr_vec, fnumbers, boost::is_any_of(" "));
// Convert the floating point numbers
std::vector<float> float_vec;
float_vec.resize(fstr_vec.size());
std::transform(fstr_vec.begin(), fstr_vec.end(), float_vec.begin(),
[&](const std::string& s) {
return boost::lexical_cast<float>(s);
}
);
// Print the test case
std::cout << "== Test case " << i << std::endl;
std::cout << "Integers: ";
std::copy(int_vec.begin(), int_vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::cout << "Floats: ";
std::copy(float_vec.begin(), float_vec.end(), std::ostream_iterator<float>(std::cout, " "));
std::cout << std::endl;
std::cout << std::endl;
}
return 0;
}示例:
./prog1
1
3 2 1 4
10.3 12.1 2.9 1.9
== Test case 0
Integers: 3 2 1 4
Floats: 10.3 12.1 2.9 1.9https://stackoverflow.com/questions/19058354
复制相似问题