【问题标题】:sub string in char* in c++ with strtok to the end of the rowc ++中char *中的子字符串,strtok到行尾
【发布时间】:2014-01-07 02:17:59
【问题描述】:

我尝试在 C++ 中捕获一个输入 char* 的字符串 这是我的代码

void DBManager::printMatched(char* line, char* fileName)
{
    line = strtok(line,"Show");
    char* teamAName = strtok(line," ");
    char* teamACity = strtok(NULL,"-");
    char* teamBName = strtok(NULL," ");
    char* teamBCity = strtok(NULL,"\n");
}

这是行内的文字 "显示 abcde fghij - klmnop qrstu"

这是可变数据:

 teamAName = abcde
 teamACity = fghij
 teamBName = klmnop
 teamBCity = qrs

如何修复我需要切入行中的 teamBCity。

我在 Linux 系统上工作。

【问题讨论】:

  • 看起来问题出在调用例程中。 printMatched()怎么叫?
  • 当我调用函数时,行的末尾有 \n 但在 line = strtok(line,"Show"); \n 已关闭..
  • 请显示使用printMatched() 并打印teamBCity 的代码。我怀疑问题在于line 的参数是如何生成的,或者您的打印teamBCity 是如何产生的。

标签: c++ c text substring strtok


【解决方案1】:

我想这就是你想要的。给出你的例子并不完全确定。它显然可以改进,也许您想使用更多的 c++ish 工具?

void DBManager::printMatched(char* line, char* fileName)
{
    char* linecpy   = strdup(line);

    char* dummy     = strtok(linecpy," ");
    char* teamAName = strtok(NULL," ");
    char* teamACity = strtok(NULL," ");
          dummy     = strtok(NULL," ");
    char* teamBName = strtok(NULL," ");
    char* teamBCity = strtok(NULL," \n");

    printf("teamAName %s\n", teamAName);
    printf("teamACity %s\n", teamACity);
    printf("teamBName %s\n", teamBName);
    printf("teamBCity %s\n", teamBCity);

    // do something with strings here?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多