C++ 简单的字符串替换,不复杂的代码,但会产生疯狂的错误

标签 c++ string replace

首先感谢大家的帮助!

我得到的错误是:

Unhandled exception at 0x7c812afb (kernel32.dll) in Readerboard.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0012f8a8..

我发现问题出在这一行:

str.replace(str.find(sought), sought.size(), replacement);

它位于这个过程中:

void DisplayMessages() {

 ifstream myReadFile;
 string str;
 static string myMessages[10];
 static int i; // of course my famous i
 static int MyPosition;
 string sought;
 string replacement;

 myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
 i = 0; //the start of my array
 sought = "</td>"; // value that I want to replace with nothing
 replacement.clear();

 if(!myReadFile) // is there any error?
{
    cout << "Error opening the file! Aborting…\n";
    exit(1);
}

 if (myReadFile.is_open()) 
 {
    cout << endl;
    while (!myReadFile.eof()) 
    {
    getline(myReadFile, str);

    if (str == "<tr>")
    {       
        myReadFile.seekg(4,ios::cur);
        getline(myReadFile, str);
        str.replace(str.find(sought), sought.size(), replacement); 

        cout << str;

        myMessages[i]=str;
        i++;
    }

    }

}

i=0;
while (i < 10)
{
    cout << i << ") " << myMessages[i] << endl;
    i++;
        if (myMessages[i]=="")
        {
            break;
        }
} 

myReadFile.close();

mainMenu();
}

整个cpp文件如下所示:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void mainMenu();
void DisplayMessages();
void AddMessage();
void DeleteMessage();
void EditMessage();
void RunTests();
void CheckFile();
void CreateHtmlFile(string myMessages[10]);
/*
#define MIN     1
#define MAX     100

#define TRUE    1
#define FALSE   0
*/

int main() {
    cout << endl;
    cout << endl;
    cout << "Hello Andrew.\n";
    cout << "First you need some sort of menu.\n";

    mainMenu();

    return 0;
}


void mainMenu() {

    int Command;

    cout << endl;
    cout << endl;
    cout << endl;
    cout << "What would you like to do?\n";
//  cout << "1) Check that tests work!\n";
//  cout << "2) Check that the file exists\n";
    cout << "3) Display Messages\n";
//  cout << "4) Edit a message\n";
//  cout << "5) Add a message\n";
//  cout << "6) Delete a message\n";
    cout << "7) Exit\n";
    cout << "Enter a number: ";
    cin >> Command;

    if (Command == 3)
    {
        DisplayMessages();
    }

    if (Command == 7)
    {
        cout << "Exiting...";
        exit(EXIT_SUCCESS);
    }

    if (Command == 6)
    {
        DisplayMessages();
    }
}


void DisplayMessages() {

 ifstream myReadFile;
 string str;
 static string myMessages[10];
 static int i; // of course my famous i
 static int MyPosition;
 string sought;
 string replacement;

 myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
 i = 0; //the start of my array
 sought = "</td>"; // value that I want to replace with nothing
 replacement.clear();

 if(!myReadFile) // is there any error?
{
    cout << "Error opening the file! Aborting…\n";
    exit(1);
}

 if (myReadFile.is_open()) 
 {
    cout << endl;
    while (!myReadFile.eof()) 
    {
    getline(myReadFile, str);

    if (str == "<tr>")
    {       
        myReadFile.seekg(4,ios::cur);
        getline(myReadFile, str);
        str.replace(str.find(sought), sought.size(), replacement); 

        cout << str;

        myMessages[i]=str;
        i++;
    }

    }

}

i=0;
while (i < 10)
{
    cout << i << ") " << myMessages[i] << endl;
    i++;
        if (myMessages[i]=="")
        {
            break;
        }
} 

myReadFile.close();

mainMenu();
}

void AddMessage() {
}
/*
void DeleteMessage() {
 ifstream myReadFile;
 string str;
 static string myMessages[10];
 static int i; // of course my famous i
 static int MyPosition;
 string sought;
 string replacement;
 static int Command;

 myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
 i = 0; //the start of my array
 sought = "</b></td>"; // value that I want to replace with nothing
 replacement.clear();

 if(!myReadFile) // is there any error?
{
    cout << "Error opening the file! Aborting…\n";
    exit(1);
}

 if (myReadFile.is_open()) 
 {
    cout << endl;

    while (!myReadFile.eof()) 
    {
        getline(myReadFile, str);

        if (str == "<tr>")
        {       
            myReadFile.seekg(7,ios::cur);
            getline(myReadFile, str);
            str.replace(str.find(sought), sought.size(), replacement); 

            myMessages[i]=str;
            i++;
        }

    }

}

i=0;
while (i < 10)
{
    cout << i << ") " << myMessages[i] << endl;
    i++;
        if (myMessages[i]=="")
        {
            break;
        }
} 
myReadFile.close();

cout << "Enter the number of the message you would like to delete?\n";
cout << "Or enter 11 to go back to the main menu.\n";
cin >> Command;

while (Command >= 12)
{
    cout << "Invalid number, try again!\n";
    cout << endl;
    cout << "Enter the number of the message you would like to delete?\n";
    cout << "Or enter 11 to go back to the main menu.\n";
    cin >> Command;
}

if (Command == 11)
{
    mainMenu();
}

myMessages[Command].clear();
//clear the string
//now rebuild the htm file with the new array
CreateHtmlFile(myMessages);
}

void EditMessage() {
}

void RunTests() {
}

void CheckFile() {
}

void CreateHtmlFile(string myMessages[])
{
}

                    //File.seekg(-5); moves the inside pointer 5 characters back
                    //File.seekg(40); moves the inside pointer 40 characters forward
                    //tellg() Returns an int type, that shows the current position of the inside-pointer for reading
                    //tellp() same as above but for writing
                    //seekp() just like seekg() but for writing
*/

请帮助我,我很难过!

最佳答案

str.replace(str.find(sought), solded.size(), replacement);str.find() 没有找到什么的时候是错误的它正在寻找。 str.find() 将返回 str::npos,这不是字符串中的有效位置。因此,调用 replace 失败并出现您看到的索引超出范围异常。

将其更改为:

std::size_t foundIndex = str.find(sought);
if (foundIndex != str.npos)
    str.replace(foundIndex, sought.size(), replacement);
else
    std::cout << "Oops.. didn't find " << sought << std::endl;

如果这对您有帮助,请告诉我们。

编辑:您可能还想考虑使用 boost::algorithm::replace_all来自 Boost String Algorithms Library

关于C++ 简单的字符串替换,不复杂的代码,但会产生疯狂的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3137666/

相关文章:

c++ - 为什么我不能在带模板的派生类中使用基类的别名?

c++ - 是否可以检查名称为字符串的函数是否存在?(C++)

c++ - 氧气警告

c++ - C++对象构造方法的区别

javascript - 如何替换除第一次出现以外的所有匹配字符

c# - 在 regex.replace 中忽略区分大小写?

c++ - G++尾递归优化失败

javascript - 先按字母排序,再按数字排序

javascript - 将字符串替换为文本

linux - 我需要从多个文件中删除一行