首页 > 解决方案 > 在达到空格字符之前,如何读取未知数量的整数?(C++)

问题描述

我需要从控制台读取数字,;直到我到达空格字符。输入应如下所示:3;1 -2;-1;1 1;1;3;2. 每组数字之间可以有多个空格,我需要将每组数字插入到一个向量中。我最初的想法是这样的:

char c;
std::vector<double> coordinates;
while(std::cin >> c){
    if(c != ' ' & c != ';'){
        double a = c - 48;
        coordinates.push_back(a);
    }
}

问题在于,如果我有负数,则无法使用 ASCII 将字符转换为整数。如果有人能给我另一种方法来做这种类型的阅读,或者能给我一些建议,我将非常感激!

标签: c++

解决方案


你可以使用istream::peek

auto read_sets(std::istream& is) {
    std::vector<std::vector<double>> sets;
    std::vector<double> current_vector;

    double number;
    while (is >> number)
    {
        current_vector.push_back(number);
        switch (is.peek())
        {
            case ';': // ignore semicolons
                is.ignore(1);
                break;

            case ' ': // move to the next set
                sets.push_back(std::move(current_vector));
                current_vector.clear();
                break;

            default: // no need to handle dots and digits. EOF is handled in while condition
                break;
        }
    }
    
    sets.push_back(std::move(current_vector)); // push the last set
    return sets;
}

推荐阅读