字符串不会在拆分上更新其值
String does not update its value on split
i具有一个函数,该函数将坐标作为字符串" 1.12 1.28"。我必须将字符串分开,并将两个值分配给浮点变量(x = 1.12和y = 1.28)。问题在于,当我将字符串分开以分开其停止为字符串分配新值的值时。
在下面运行代码时,它会打印整个字符串并在每次迭代时进行更新。
void print_coordinates(string msg, char delim[2])
{
cout << msg;
cout << "n";
}
int main()
{
SerialIO s("/dev/cu.usbmodem1441");
while(true) {
print_coordinates(s.read(), " ");
}
return 0;
}
输出:
1.2 1.4
1.6 1.8
3.2 1.2
但是,当我在下面运行代码时停止更新字符串。
void print_coordinates(string msg, char delim[2])
{
float x = 0;
float y = 0;
vector<string> result;
boost::split(result, msg, boost::is_any_of(delim));
x = strtof((result[0]).c_str(), 0);
y = strtof((result[1]).c_str(), 0);
cout << x;
cout << " ";
cout << y;
cout << "n";
}
int main()
{
SerialIO s("/dev/cu.usbmodem1441");
while(true) {
print_coordinates(s.read(), " ");
}
return 0;
}
输出:
1.2 1.4
1.2 1.4
1.2 1.4
如果要使用boost,则可以使用boost :: tokenizer。
但是您无需使用Boost将字符串分开。如果您的分隔符是Whitespace字符" "
,则可以简单地使用std :: stringsstream。
void print_coordinates(std::string msg)
{
std::istringstream iss(msg);
float x = 0;
float y = 0;
iss >> x >> y;
std::cout << "x = " << x << ", y = " << y << std::endl;
}
如果要指定分配器
void print_coordinates(std::string msg, char delim)
{
std::istringstream iss(msg);
std::vector<float> coordinates;
for(std::string field; std::getline(iss, field, delim); )
{
coordinates.push_back(::atof(field.c_str()));
}
std::cout << "x = " << coordinates[0] << ", y = " << coordinates[1] << std::endl;
}
相关文章:
- 从C++本机插件更新Vector3数组
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- C++将向量的向量拆分为向量的N个子向量
- cmake更新缓存的变量
- 更新到莫哈韦后出现cmath错误
- OpenMP:并行更新数组总是需要减少数组吗
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 指针没有更新它在void函数内部指向的值
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 如何在c++中获取要更新的值
- 已修改的LinkedList未在文本文件本身中更新
- Qt:当QListView获得新条目时,如何更新QStringList
- 更新的矢量元素不打印
- OpenCV 4.1.2 - 从网络摄像头获取帧并将其拆分
- 如何使用按钮更新GTK3图像以使用C++从相机捕获图片
- 如何在ECS框架中更新组件数据和通知系统
- 从VS 2015更新3更新到VS2015更新3 d后浮点计算行为不同的原因
- 如果我想在没有更新编译器的情况下使用新功能,该怎么办?
- 使用 C++ 将命令行参数拆分为参数/向量
- 字符串不会在拆分上更新其值