输入大小未知cin

时间:2015-04-30 21:01:11

标签: 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

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

有两个不同的问题:(a)读取未知数量的输入行;(b)将给定的输入行解析为未知数量的int s。

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

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

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

std::istringstream iss(str);

然后逐一阅读int

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

或者通过传递一对istream_iterator<int>来将所有这些内容同时放入vector

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';
    }
}

答案 1 :(得分:3)

这对于家庭作业和比赛问题非常普遍,答案如下:

#include <sstream> //you may not have known about this

int num_cases = 0;
std::cin >> num_cases;
for(int case_num=0; case_num<num_cases; ++case_num) { //for each case       
    std::vector<std::vector<int>> variables;
    int num_variables = 0;
    std::cin >> num_variables;
    std::cin.ignore(1); //ignore the newline character, it messes with getline
    for(int var=0; var<num_variables; ++var) { //for each variable
        std::string linestr;
        std::getline(std::cin, linestr, '\n'); //read whole line into string
        std::istringstream linestream(linestr); //make a stream from the line

        int newclause = 0;
        std::vector<int> lineclauses;
        while(linestream >> newclause) //for each clause
            lineclauses.push_back(newclause); //add it to the row
        //when that fails, we read the whole line
        variables.push_back(lineclauses); //so add the row to 'variables'
    }
    //Do stuff with variables vector.
}