c++ - 用指针搜索和替换

标签 c++ pointers strstr

我正在尝试实现“搜索并替换所有”。我有 2 个指针来监视字符 nclude #包括 #包括 使用命名空间标准;

const int BUFSIZE = 256;

const char * const SEARCH = "the";
const char * const REPLACE = "Who is John";

int main()
{
    char buf[BUFSIZE];
      Error(SOURCE_FILE);

    //open file for append and update
    fstream destination(DESTINATION_FILE, 
        ios_base::in | ios_base::out | ios_base::app);

    //check if destination file is open
    if (!destination.is_open())
        Error(SOURCE_FILE);


        bufPtr += length;               //move bufPtr to point past the SEARCH

        destination << bufPtr;          //write rest of buf to destination
        //destination.seekg(0);

        //write lines from source to destination
        //if(!(destination << buf << '\n'))
            //Error(SOURCE_FILE);
    }   
    source.close();
    destination.close();

    return 0;
}

最佳答案

您没有检查 strstr() 找不到搜索字符串的情况。在那种情况下它返回 NULL,而你的 while 循环在那种情况下不会做正确的事情。

关于c++ - 用指针搜索和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135969/

相关文章:

c++ - 是否有任何库可以确定一个数值是否可以转换为特定字符集中的有效、可打印且有意义的字符?

c - 有符号字符指针和无符号字符指针之间的工作区别是什么?

c for循环break语句不起作用

c - 如何检查子字符串的实例是否在字符串的末尾并且仅一次(比如使用 strstr)?

c - 尝试在 C 中引用值时出现 LValue 错误

php - 有没有PHP函数可以找到中间字符串?

C++ 在方法中传递 const 字符串引用?

c++ - 从具有非虚拟析构函数的容器继承

c++ - 有人可以向我解释此链接列表如何工作吗?

c - Kdtree插入函数