c++删除(0,1);在字符串中,删除文件中字符的所有实例

C++ Erase(0,1); in string, removing all instances of character in file

本文关键字:删除 字符 文件 实例 c++ 字符串      更新时间:2023-10-16

我有一个程序在'isMemLoc()'函数中检查"@",如果它找到一个,它应该删除它。(此符号将始终是该行的第一个字符,因此erase(0,1)调用

#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}
bool isComment(string line){
    string comment = "/";
    if(line.find(comment) != string::npos){
        return true;
    }else{
        return false;
    }
}
bool isMemLoc(string line){
    string symbol = "@";
    if(line.find(symbol) != string::npos){
        cout << "CONSTANT FOUND" << endl;
        //ConvertToBinary(atoi(line.c_str));
        return true;
    }else{
        return false;
    }
}

 int main( int argc, const char* argv[] )
{
    string outLine = "test output";
    string file1 = argv[1];
    cout << "before: " << file1 << endl;
    replace(file1, "asm", "hack");
    cout << "after: " << file1 << endl;
    //input
    //WHILE READ LINE()
    ifstream infile(argv[1]);
    string tempLine;
    ofstream outfile(file1.c_str());
    while (getline(infile, tempLine)){
        if(isComment(tempLine))
            continue;
        if(isMemLoc(tempLine)){
            tempLine.erase(0);
            cout << tempLine << endl;
            outfile << tempLine << std::endl;
            continue;
        }
        //print to terminal and pass to file
        cout << tempLine << endl;   
        outfile << tempLine << std::endl;
    }
    outfile.close();
}

然而,当它找到这个字符时,我的程序也删除了所有找到这个值的行,例如:

1
2
3
13 
@12
@12
@13
2

变成

1
2
3
13 
2

这是不希望的。我做错了什么?

首先,你的问题中有这个(这是正确的):

tempLine.erase(0, 1);

然后,您将代码更改为(我想这是原始代码):

tempLine.erase(0);

查看参考资料,您会发现count参数默认为std::string::npos -擦除字符直到结束