C ++ "нет совпадения для" operator- "при преобразовании char в int - PullRequest
0 голосов
/ 13 октября 2018

Я пытаюсь получить от пользователя несколько строк ввода, каждая строка содержит два числа, разделенных пробелом:

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 голосов
/ 13 октября 2018

Прежде всего, 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);
}
0 голосов
/ 13 октября 2018

Я не большой поклонник чтения чего-либо из одного потока, просто чтобы вставить это в другой.

#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;
    }
}
...