制作角色扮演游戏并希望货币以铂金、黄金、白银和铜表示。不幸的是,我的教授希望将货币存储为字符串(即字符串类,而不是 cStrings)。例如 -- 0.1.23.15 表示 0 铂金、1 黄金、23 银和 15 铜。
我只是想知道如何实现它的重要想法。例如——我可以使用 strtok(即我相信这只适用于 cStrings)或其他一些 C++ 函数来完成这个吗?
最佳答案
这是一种解决方案:
#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;
}
关于c++ - 如何将字符串转换为一系列整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823185/