c++ - 未知输入大小 cin

标签 c++ input cin

我确定这是一个简单的问题。老实说,这应该是编写 SAT 求解器最简单的部分,但是,我应该让用户输入这样的数据:

Sample Input:
1              <-- 1st number denotes the number of cases I will have
5              <-- 2nd number represents the number of variables, followed 
1 2 3              who knows how many clauses.
-1 3 4
-2 -3 5
-5 -1 2
-4 1 -2
-4 -1 -2 -3 -5

*blank line separates the different cases*
.... followed by as many cases as the user said they had

因此,我将这些子句存储到字符串 vector 中,然后它们都将存储到另一个 vector 中。那么从用户那里获得这种输入的最佳方式是什么?最初没有给出条款数量的事实是最让我困惑的部分。我会尝试一段时间()...但我不知道如何终止它。我想我有点不确定 cin 在这种情况下如何工作。

感谢您的帮助。

最佳答案

有两个独立的问题:(a) 读取未知数量的输入行和 (b) 将给定的输入行解析为未知数量的 int秒。

首先,从输入中读取行。那只是 std::getline :

std::string str
while (std::getline(std::cin, str)) {
    // ???
}

然后,给定str ,我们必须将其解析为 int秒。最简单的方法是将其放入 stream 中:

std::istringstream iss(str);

然后要么阅读int一个一个:

int i;
while (iss >> i) {
    // do something
}

或者将它们全部放入vector立即传递一对 istream_iterator<int> :

std::vector<int> v{std::istream_iterator<int>{iss},
                   std::istream_iterator<int>{}};

因此,记录每行输入总和的完整示例将是:

std::string str
while (std::getline(std::cin, str)) {
    std::istringstream iss(str);
    std::vector<int> v{std::istream_iterator<int>{iss},
                       std::istream_iterator<int>{}};

    if (!v.empty()) {
        std::cout << "sum=" << std::accumulate(v.begin(), v.end(), 0) << '\n';
    }
}

关于c++ - 未知输入大小 cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977684/

相关文章:

C++如何检查Shell输入的数量

c++ - 在 GCC 中实现 Borland 的 __emit__ 宏

c++ - 动态分配的内存未在 SSE 中对齐

c++ - 如何创建一个简单的 cpu 基准测试?

c++ - 模板元代码和私有(private)成员

c++ - 使用>>链检查非整数输入(C++)

html - 仅当上一个文件输入不为空时才显示文件输入

javascript - 阻止网页上的语音输入?

java - 为参数化构造函数获取值的方法

c++ - 手动设置 cin.fail()