当将char转换为int时,C ++“不匹配'operator-'”

时间:2018-10-13 14:14:02

标签: c++ iostream

我正在尝试从用户那里获取多行输入,每行包含两个用空格分隔的数字:

4 7
15 21
32 78

到目前为止,我的代码是:

vector<string> lines;
string line;
int m, n;
while (true) 
{
    cin >> line;

    if (line != "") 
    {
        lines.push_back(line);
    }
    else 
    {
        break;
    }
}
for (string i: lines) 
{
    istringstream iss(i);
    vector<string> results((istream_iterator<string>(iss)), istream_iterator<string>());

    if (typeid(results[0]).name() == "char") 
    {
        m = results[0] - '0';
    }
    else 
    {
        m = atoi(results[0]);
    }

    if (typeid(results[1]).name() == "string") 
    {
        n = results[1] - '0';
    }
    else 
    {
        n = atoi(results[1]);
    }

    calculate(m, n);
}

我在m = results[0] - '0'遇到错误。它说

error: no match for 'operator-' (operand types are 
'__gnu_cxx:__alloc_traits<std::allocator<std::__cxx11::basic_string<char> > 
>::value_type {aka std::__cxx11::basic_string<char>}' and 'char')

总有办法解决此问题,以便将每一行中的每个数字都分成一个整数变量吗?

2 个答案:

答案 0 :(得分:0)

我不喜欢从一个流中读取某些内容,只是将其填充到另一个流中。

#include <cctype>
#include <limits>
#include <cstdlib>
#include <iostream>

std::istream& eatws(std::istream &is)  // eats up whitespace until '\n' or EOF
{
    int ch;
    while ((ch = is.peek()) != EOF && ch != '\n' &&
           std::isspace(static_cast<char unsigned>(ch)))  // don't pass negative
        is.get();                                         // values to isspace()
    return is;
}

int main()
{
    int a, b;  // not a fan of variable names like m and n
               // or i and j next to each other either.
    bool empty_input{ false };

    while ((std::cin >> eatws) && (empty_input = std::cin.peek() == '\n') ||  // empty line
           (std::cin >> a >> b >> eatws) && std::cin.get() == '\n')  // valid imput
    {
        if (empty_input)
            break;

        std::cout << "Do something with " << a << " and " << b << ".\n";
    }

    if (!empty_input) {  // if we reach this point and the last input was not empty
        std::cerr << "Input error!\n\n";  // some garbage has been entered.
        return EXIT_FAILURE;
    }
}

答案 1 :(得分:0)

首先,cin只会读到空格为止,因此您只会得到第一个数字。其次,您可以直接进行cin >> m >> n并让cin处理字符串解析,而不是尝试将字符串手动转换为数字等。我想如果您正在寻找一个空行来结束输入,那么您将想要这样做:

vector<string> lines;
while (true) 
{
    string line;
    getline(cin, line);

    if (line != "") 
    {
        lines.push_back(line);
    }
    else 
    {
        break;
    }
}
for (string line: lines) 
{
    int m, n;
    istringstream iss(line);

    iss >> m >> n;

    calculate(m, n);
}