c++ - C ++中的字符串标记化引发段错误
问题描述
我想编写一个按标记分解字符串的函数,到目前为止我想出了以下内容:
#include <cstring>
#include <iostream>
#include <vector>
#define MAXLEN 20
void mytoken(std::string input, std::vector<std::string> & out);
int main()
{
std::vector<std::string> out;
std::string txt = "XXXXXX-CA";
mytoken(txt, out);
std::cout << "0: " << out[0] <<std::endl;
std::cout << "1: " << out[1] <<std::endl;
}
void mytoken(std::string instr, std::vector<std::string> & out) {
std::vector<std::string> vec;
char input[MAXLEN] = {0};
strcpy(input, instr.c_str());
char *token = std::strtok(input, "-");
while (token != NULL) {
std::cout << token << '\n';
token = std::strtok(NULL, "-");
out.push_back(token);
}
}
产生以下输出:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
XXXXXX
CA
bash: line 7: 21987 Aborted (core dumped) ./a.out
我想知道为什么会这样。
解决方案
最好使用 'c++-style' 函数:它更简单,更易读:
#include <sstream>
void mytoken(std::string instr, std::vector<std::string> & out)
{
std::istringstream ss(instr);
std::string token;
while(std::getline(ss, token, '-'))
{
std::cout << token << '\n';
out.push_back(token);
}
}
为了使您的示例正常工作,您需要更改循环中的操作顺序:
//...
while(token != NULL)
{
out.push_back(token);
std::cout << token << '\n';
token = std::strtok(NULL, "-");
}
推荐阅读
- python - Python 到 csv 文件
- c# - Microsoft 同步框架在配置时增加了数据库大小
- javascript - 工作函数如何返回另一个接受另一个参数的函数?
- c# - 如何将我的表(数据库)的列名显示到组合框中
- database - 在 MongoDB 中,如何检索字段 X 大于字段 Y 的值 N 的一组结果?
- android - 从 RecyclerView 适配器获取 EditText 值
- swift - URLSessionConfiguration 背景,超时问题,在 Postman 中工作正常
- python - Python 文档字符串中作为抽象类名的参数的类型是什么?
- python - Select 语句中的 Pace Maker 不起作用
- c++ - 为 I2C 正确格式化数据 (Wire.write)