我确信这是一个简单的问题.老实说,这应该是编写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
Run Code Online (Sandbox Code Playgroud)
所以,我将这些子句存储到字符串向量中,并且它们都会进入另一个向量.那么从用户那里获得此输入的最佳方法是什么?最初没有给出条款数量的事实是让我感到困惑的部分.我会尝试一会儿()...但我不知道如何终止它.我想我有点不确定cin在这种情况下会如何工作.
感谢你的帮助.
存在两个单独的问题:(a)读取未知数量的输入行和(b)将给定的输入行解析为未知量的ints.
首先,从输入中读取行.那只是std::getline:
std::string str
while (std::getline(std::cin, str)) {
// ???
}
Run Code Online (Sandbox Code Playgroud)
然后,给定str,我们必须将其解析为ints.最简单的方法是将其放入流中:
std::istringstream iss(str);
Run Code Online (Sandbox Code Playgroud)
然后要么int逐个阅读:
int i;
while (iss >> i) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
或者vector通过传递一对来将它们全部放入istream_iterator<int>:
std::vector<int> v{std::istream_iterator<int>{iss},
std::istream_iterator<int>{}};
Run Code Online (Sandbox Code Playgroud)
因此,记录每行输入总和的完整示例将是:
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';
}
}
Run Code Online (Sandbox Code Playgroud)