如何使用 cin 处理以下输入

How do I process following kind of input using cin?

本文关键字:输入 处理 何使用 cin      更新时间:2023-10-16

输入如下:

2
3 2 1 4
10.3 12.1 2.9 1.9
2 1 3
9.8 2.3 1.2

所以 2 是测试用例的数量。然后有一个空行。然后是测试用例。单个测试由两行分别是整数值和浮点值组成。整数数等于浮点值数。然后再次出现一个空行,然后是第二个测试。
我面临两个问题:首先,如果我知道将有多少个数字,我可以用于循环,第二个在测试用例之后和测试用例之间有空行。我不知道如何使用 cin 阅读它们或忽略它们。我将把这些值存储在向量中。谢谢

您可以使用

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,阅读下一行带有浮点数应该很容易。只需使用循环,因为您知道浮点数与每个测试用例的整数数相同。

我认为以下程序可以满足您的需求。

#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.9