c++ - 字符串不会在拆分时更新其值

标签 c++

我有一个函数接收坐标作为字符串“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 来分隔字符串。 如果您的分隔符是空白字符 "",您可以简单地使用 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++ - 字符串不会在拆分时更新其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238572/

相关文章:

c++ - ~ 和 - 之间的区别

c++ - 依赖隐式声明的 move 构造函数是否安全?

c++ - 如何从 LPWSTR 转换为 'const char*'

c++ - 在 MainWindow 中看不到我的标签和布局

c++ - Green Hills Integrity 动态内存分配

c++ - 在纯 C++ (C++11) 中扩充一个类/应用一个方面

c++ - 复制构造函数不调用

c++ - Boost.ASIO 如何将链与 c++20 协程一起使用

c++ - 将不可访问的私有(private)基类型的指针传递给派生类方法

c++ - 了解 FMA 性能