【问题标题】:How to fix 'No matching function for call to 'strtok'' [duplicate]如何修复'没有匹配的函数调用'strtok'' [重复]
【发布时间】:2019-12-15 23:09:18
【问题描述】:

我正在尝试使用函数 strtok 来标记来自用户的输入,然后在每个单词之间用新行打印出结果。但是,会弹出此错误。

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    string str;
    char *tokenPtr;

    cout << "Enter a sentence : " << endl;
    getline(cin, str);

    tokenPtr = strtok( str, " " ); // ERROR: No matching function for call to 'strtok'
    while( tokenPtr != NULL ) {
        cout << tokenPtr << endl;
        tokenPtr = strtok( NULL, " " );
    }

    return 0;
}

【问题讨论】:

  • @Naoki Atkins strtok 在您尝试将它与 std::string 类型的对象一起使用时与字符数组一起使用。
  • 您可以随时使用 str.c_str() 将其转换为 const char *。
  • @TheMarlboroMan strtok 采用指向 char 的指针,因为它修改了数组
  • @VTT,对不起,我的意思是通过从 c_str() 复制来创建 char *...
  • @TheMarlboroMan 为什么使用流很糟糕?!

标签: c++ string split istringstream strtol


【解决方案1】:

标准 C 函数 strtok 用于包含字符串的字符数组。

因此,当您提供std::string 类型的参数时,它的第一个参数的类型为char *

您可以改用标准字符串流std::istringstream,例如

#include <iostream>
#include <string>
#include <sstream>

int main() 
{
    std::string s;

    std::cout << "Enter a sentence : ";

    std::getline( std::cin, s, '\n' );

    std::string word;

    for ( std::istringstream is( s ); is >> word; )
    {
        std::cout << word << '\n';
    }

    return 0;
}

程序输出可能看起来像

Enter a sentence : Hello Naoki Atkins
Hello
Naoki
Atkins

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-06
    • 2019-10-09
    • 2020-09-13
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2020-02-18
    相关资源
    最近更新 更多