使用strstr()函数是错误的
using strstr() function is breaking
我正在使用strstr()
函数,但我正在崩溃。
这部分代码崩溃,错误"读取位置0x0000006c."strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
这是完整的代码…
#include "stdafx.h"
#include <iostream>
#include <string>
void delchar(char* p_czInputString, const char* p_czCharactersToDelete)
{
for (size_t index = 0; index < strlen(p_czInputString); ++index)
{
if(NULL != strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]))
{
printf_s("%c",p_czInputString[index]);
}
}
}
int main(int argc, char* argv[])
{
char c[32];
strncpy_s(c, "life of pie", 32);
delchar(c, "def");
// will output 'li o pi'
std::cout << c << std::endl;
}
strstr()
的原型如下,
char * strstr ( char * str1, const char * str2 );
函数用于从主字符串中定位子字符串。它返回一个指向str1
中str2
第一次出现的指针,或者如果str2
不是str1
的一部分,则返回一个空指针。
在您的情况下,您正在传递错误的参数给strstr()
。你在呼唤,strstr(p_czCharactersToDelete, (const char*)p_czInputString[index]));
,是错误的。因为指针p_czCharactersToDelete
指向子字符串常量,而p_czInputString
指向主字符串。将strstr()
调用为strstr(p_czInputString, p_czCharactersToDelete);
,并对函数delchar()
进行相应的修改。
您正在使用错误的strstr
。也许你需要strchr
或strpbrk
。
#include <cstring>
#include <algorithm>
class Include {
public:
Include(const char *list){ m_list = list; }
bool operator()(char ch) const
{
return ( strchr(m_list, ch) != NULL );
}
private:
const char *m_list;
};
void delchar(char* p_czInputString, const char* p_czCharactersToDelete){
Include inc(p_czCharactersToDelete);
char *last = std::remove_if(p_czInputString, p_czInputString + strlen(p_czInputString), inc);
*last = ' ';
}
相关文章:
- 链接器错误:函数的多个定义
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:函数声明符之后的预期函数体
- C 错误 - 函数不能超载
- 如何修复传递参数时调用错误函数的主函数?(C++)
- 错误:函数调用中有两个参数
- 错误:函数不是“类”的静态数据成员 - C++
- C ,G 编译错误函数
- CMake 解析错误函数缺少结尾")"。而是找到带有文本的未终止字符串")
- C++ 错误 函数 2 的多重定义
- 错误:函数调用中从int到int(*)[4]的转换无效
- C++14 自动扣除错误:函数返回一个数组
- 视觉C++错误:函数必须返回一个值
- 错误:函数声明中的两种或多种数据类型
- 错误:函数未在作用域中声明
- rtw_android.c错误:函数“strnicmp”的隐式声明[-Weror=隐式函数声明]
- 错误:函数中的return语句没有值,返回“void*”[-fpermission]
- 简单程序中的链接器错误:函数的多重定义
- 错误:函数参数太多
- 错误:函数__tmaincrtstartup中引用的未解析的外部符号_main