【问题标题】:C++ exception: std::out_of_range at memory location 0x003DF4C0 [duplicate]C ++异常:内存位置0x003DF4C0处的std :: out_of_range [重复]
【发布时间】:2019-09-16 06:56:03
【问题描述】:

我正在制作一个 C++ 程序,它可以从电话列表中获取电话并从中制作一个 vCard 文件。但是,我在将电话复制到文件时遇到了问题,这是模板的字符串替换。我该如何解决这个问题?

我已经尝试在这个网站上寻找一些解决方案,但没有一个是关于 ofstream 的,这是我用来做这件事的。

int main()
{
    string fileDest;

    string vCardTemp = "BEGIN:VCARD\nVERSION:3.0\nTEL;TYPE=WORK,MSG: phonehh\nEND:VCARD\n";

    cout << "Input file destination...\n"; 

    cin >> fileDest;

    cout << "Analyzing data...";


    ifstream inFile;
    inFile.open(fileDest);

    if (!inFile)
    {
        cout << "Error! File doesn't exist or can't be opened.";
        cin.ignore();
        exit(0);
    }

    cout << "File found. Dissecting...";

    string line;

    string finalvCard = "";
    string copy = vCardTemp;
    while (getline(inFile, line))
    {
        istringstream iss(line);

        copy.replace(copy.find("phonehh"), 7, line);

        //finalvCard += copy;
        finalvCard.append(copy);

        cout << " - " + line + " written to vCard.\n";
    }

    cout << "\n\nFinished vCard conversion. Where do we store this (include filename)?\n";

    string dest;

    cin >> dest;

    ofstream file(dest);
    file << finalvCard;

    cout << "File stored! Cya!\n";
    return 0;
}

【问题讨论】:

  • copy.replace(copy.find("phonehh"), 7, line); 可能会导致此问题。如果查找不成功怎么办?

标签: c++ visual-studio c++11 fstream ofstream


【解决方案1】:

这是另一个问题的重复:C++ simple string replace, non complicated code, but producing crazy error

@Billy ONeal 有一个很好的解释,我将在此重复: 当str.find() 没有找到它正在寻找的东西时,str.replace(str.find(sought), sought.size(), replacement); 是错误的。 str.find() 将返回 str::npos,这将不是字符串中的有效位置。因此,replace 调用失败,您看到的索引超出范围异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2016-09-23
    • 2013-08-03
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多