Strtok():标记化字符串
Strtok(): Tokenizing string
我不断收到一个错误,说"调用'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>
相关文章:
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- C++ 使用 Strtok 读取字符串字符时出错
- 拆分C++字符串(使用 strtok?),由逗号分隔,不使用外部库
- Strtok似乎没有修改输入字符串
- strtok():将字符串转换为char*
- 使用 strtok 查找子字符串
- strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记
- Strtok():标记化字符串
- C++ 中 char* 中的子字符串,行尾带有 strtok
- 字符串上strtok()的C++用法
- 使用strtok复制字符串部分时出现内存错误
- 使用 strtok 在条件下拆分字符串
- 使用 strtok() 的错误字符串比较
- 比较 strtok 之后的字符串
- 使用 strtok 拆分字符串
- 将字符串添加到 vector<const char *> 会给 strtok() 带来奇怪的行为
- 如何使"strtok function"一次使用多个令牌字符串? 函数指针会解决这个问题吗?
- 将字符串分隔为分隔符strtok (c++)
- 尝试对字符串使用"strtok"时出错
- c++ strtok in函数将原始字符串值更改为参数