【问题标题】:How can I split a string of Numbers and multiply the separate numbers?如何拆分一串数字并将单独的数字相乘?
【发布时间】:2020-11-22 17:19:45
【问题描述】:

我在一个字符串中有两个单独的数字。我想出了如何用分隔符分割字符串(输出为 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. 在分隔符处拆分字符串,2. 将单个字符串转换为整数,3. 将整数相乘。你看起来像你有#1。但是你试图在没有先完成 #2 的情况下进入 #3。查看std::atoistd:stol 系列函数。偏好后者为“更像C++”
  • @bipll:是的,它们被写在一个字符串中......将尝试转换。谢谢大家!

标签: c++ string split delimiter


【解决方案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;

}

【讨论】:

  • 如果正好有 2 个数字,为​​什么还需要 while 循环?
  • 是的。这只是一个例子。实际输入是两个字符串,每个字符串包含两个数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多