C++比较并替换stringstream的最后一个字符

C++ Compare and replace last character of stringstream

我想检查以下内容:

  1. 如果附加到 stringstream 的最后一个字符是逗号。
  2. 如果是删除它。

std::stringstream str;
str << "["
//loop which adds several strings separated by commas

str.seekp(-1, str.cur); // this is to remove the last comma before closing bracket

str<< "]";

问题是如果循环中没有添加任何内容,左括号将从字符串中删除。所以我需要一种方法来检查最后一个字符是否是逗号。我是这样做的:

if (str.str().substr(str.str().length() - 1) == ",")
{
    str.seekp(-1, rteStr.cur);
}

但是我对此感觉不是很好。有更好的方法吗?

关于循环:

循环用于标记通过套接字接收的一组命令,并将其格式化以通过另一个套接字发送到另一个程序。每个命令都以 OVER 标志结束。

std::regex tok_pat("[^\[\\",\]]+");
std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
std::sregex_token_iterator tok_end;
std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);
while (baseStr == "OVER")
{
    //extract command parameters
    str << "extracted_parameters" << ","
}

我经常处理这些循环的方式是你想在 space 或逗号 之间放置一些东西 项目列表是这样的:

int main()
{
    // initially the separator is empty
    auto sep = "";

    for(int i = 0; i < 5; ++i)
    {
        std::cout << sep << i;
        sep = ", "; // make the separator a comma after first item
    }
}

输出:

0, 1, 2, 3, 4

如果你想让它更有效率,你可以在进入循环之前使用 if() 输出第一个项目以输出其余项目,如下所示:

int main()
{
    int n;

    std::cin >> n;

    int i = 0;

    if(i < n) // check for no output
        std::cout << i;

    for(++i; i < n; ++i) // rest of the output (if any)
        std::cout << ", " << i; // separate these
}

在你的情况下,第一个解决方案可以这样工作:

    std::regex tok_pat("[^\[\\",\]]+");
    std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
    std::sregex_token_iterator tok_end;
    std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);

    auto sep = ""; // empty separator for first item

    while (baseStr == "OVER")
    {
        // extract command parameters
        str << sep << "extracted_parameters";
        sep = ","; // make it a comma after first item
    }

第二个(可能更省时)解决方案:

    std::regex tok_pat("[^\[\\",\]]+");
    std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
    std::sregex_token_iterator tok_end;
    std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);

    if (baseStr == "OVER")
    {
        // extract command parameters
        str << "extracted_parameters";
    }

    while (baseStr == "OVER")
    {
        // extract command parameters
        str << "," << "extracted_parameters"; // add a comma after first item
    }