【问题标题】:How to convert a string to a series of integers?如何将字符串转换为一系列整数?
【发布时间】:2013-04-04 22:59:35
【问题描述】:

制作 RPG 并希望以铂金、金、银和铜表示货币。不幸的是,我的教授希望将货币存储为字符串(即字符串类,而不是 cStrings)。例如 -- 0.1.23.15 将是 0 铂、1 金、23 银和 15 铜。

我只是想知道如何实现这一点。例如——我可以使用 strtok(即我相信这仅适用于 cStrings)或其他一些 C++ 函数来完成此操作吗?

【问题讨论】:

  • 使用findsubstr,还有你的strtok?
  • 这里有一个关于拆分字符串的好问题。还有一个std::split 提案正在进行中,但我认为你的教授不能等那么久:p
  • sscanf 在您的字符串的 c_str() 上?匹配模式“%d.%d.%d.%d”

标签: c++ string type-conversion


【解决方案1】:

这里有一个解决方案:

#include <iostream>
#include <sstream>
#include <vector>

using namespace std;


int main()
{
    string str="0.1.23.15",temp;
    stringstream s(str);
    vector<int> v;

    while(getline(s,temp,'.'))
    {
        v.push_back(stoi(temp));
    }

    for(int i: v) cout << i << endl;//C++11 style
    //for(int i=0; i<v.size(); i++) cout << v[i] << endl; //Old school :D
    system("pause");
    return 0;
}

【讨论】:

  • +1 这很好,但是当您可以使用std::cin.get(),不需要using namespace std 并且基于for循环的范围在技术上不一样时,您不需要 system("pause")它下面的常规for循环。
猜你喜欢
  • 2021-06-16
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多