Search code examples
c++fileerase

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


I have a program that checks for "@" in the 'isMemLoc()' function, and if it finds one it should remove it. (this symbol will always be the first character on the line, hence the erase(0,1) call

#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();
}

However, when it finds this character, my program is also deleting all of the lines where this value is found eg:

1
2
3
13 
@12
@12
@13
2

turns into

1
2
3
13 
2

This is undesired. What am I doing wrong?


Solution

  • First, you had this in your question (which was right):

    tempLine.erase(0, 1);
    

    Then, you changed the code to this (I suppose it's the original one):

    tempLine.erase(0);
    

    See reference and you'll find out that the count parameter is defaulted to std::string::npos - erases characters till end.