提问者:小点点

我怎样才能拆分一串数字,然后将分开的数字相乘?


我在一个字符串中有两个独立的数字。 我知道了如何用分隔符拆分字符串(输出值为136),但我仍然无法解决如何将两个数字相乘并将结果存储在变量中的问题。 有什么提示吗?

#include <iostream>
#include <string>

int main()

{
    std::string b = "13,6";
    std::string delimiter = ",";
    size_t pos = 0;
    std::string token;

    while ((pos = b.find(delimiter)) != std::string::npos) {
        token = b.substr(0, pos);
        std::cout << token;
        
        b.erase(0, pos + delimiter.length());
    }

    std::cout << b;

}

共1个答案

匿名用户

多亏了你:

#include <iostream>
#include <string>


int main()

{
    std::string b = "13,6";
    std::string delimiter = ",";
    size_t pos = 0;
    std::string token;
    int number1;
    int number2;

    while ((pos = b.find(delimiter)) != std::string::npos) {
        token = b.substr(0, pos);
        number1 = std::stoi(token);

        b.erase(0, pos + delimiter.length());
    }
    number2 = std::stoi(b);
    std::cout << number1*number2;

}