我想将这样的数字列表分开:34,45,12.3,100,34.6,50
只有当数字没有小数点时,我才能够做到这一点:
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "34,45,12.3,100,34.6,50";
std::vector<int> vect;
std::stringstream ss(str);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
for (i=0; i< vect.size(); i++)
std::cout << vect.at(i)<<std::endl;
}
这里的问题在于小数。上述代码将会产生以下结果:
34 45 12 3 100 34 6 50
虽然它应该产生:
34 45 12.3 100 34.6 50
基本上,当上面的代码看到一个点'.'
时,它会像看到逗号一样处理。
有什么想法吗?
int
向量,因此它不能存储浮点数;浮点数将被截断为整数部分。将你的向量更改为其元素为浮点数。 - bku_drytti
应该是一个float
。 - Chnossosi
。) - Mateen Ulhaq34 45 12 3 100 34 6 50
- 使用哪种编译器/版本和语言环境?通常我只希望它只产生34 45 12
,因为在12.3
中的.
应该导致while (ss >> i)
循环终止,事实上,在我的测试中,在设置为英语的 Win7 上的 VS2013 / MSVC12 上仅得到34 45 12
。 - Tony Delroy