Strtok():标记化字符串

Strtok(): Tokenizing string

本文关键字:字符串 Strtok      更新时间:2023-10-16

我不断收到一个错误,说"调用'strtok'没有匹配的函数"。我不太擅长编码,很困惑 D:

我正在读取的文件中的行示例:威尔科 威尔科 2009 无唱片 11 58 摇滚

int find_oldest_album(Album **& albums, int num_of_albums){
    string line;
    ifstream fin;
    fin.open("/Users/ms/Desktop/albums.txt");
    while (!fin.eof())
    {
        getline(fin, line, 'n');
        char * artist_name;
        char artist_name = strtok(line, 't');
        char * title_name;
        title_name = strtok(NULL, 't');
        char  * release_year;
        release_year = strtok(NULL, 't');
    }

    fin.close();
}
strtok函数

只能应用于字符数组。这是一个 C 标准函数。如果要以与使用 strtok 相同的方式分析类型std::string的对象,则应使用在标头 <sstream> 中声明的标准流类std::istringstream

例如

#include <sstream>
//...
std::string line;
std::getline( fin, line, 'n' );
std::istringstream is( line );
std::string artist_name;
std::getline( is, artist_name, 't' );

至于你的代码,它包含许多错误。

例如在这两个语句中

   char * artist_name;
   char artist_name = strtok(line, 't');

有三个错误。您正在重新声明名称artist_name,函数strtok不能与类型std::string的对象一起使用,并且函数strtok的第二个参数,分隔符,必须指定为字符串,它具有类型const char *

strtok是一个损坏的C函数,不应使用。 它需要一个可写 C 字符串(不是 std::string ),并且它具有静态状态,其中很容易被损坏。

如果您的行具有标准分隔符,例如制表符,编写一个函数将它们分解为字段很容易:

std::vector<std::string>
split( std::string const& line )
{
    std::vector<std::string> results;
    std::string::const_iterator end = line.end();
    std::string::const_iterator current = line.start();
    std::string::const_iterator next = std::find( current, end, 't' );
    while ( next != end ) {
        results.push_back( std::string( current, next ) );
        current = next + 1;
        next = std::find( current, end, 't' );
    }
    results.push_back( std::string( current, end ) );
    return results;
}

更一般地说,对于任何解析问题,只需遍历字符串,如上。

使用C++的更好解决方案由Mosco的vlad在他的回答中概述。要解决错误"调用'strtok'没有匹配的功能",您需要包含头文件,如下所示:

#include<cstring>