【问题标题】:C++ Erase(0,1); in string, removing all instances of character in fileC++ 擦除(0,1);在字符串中,删除文件中的所有字符实例
【发布时间】:2015-05-30 16:28:52
【问题描述】:

我有一个程序在 '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

这是不受欢迎的。我做错了什么?

【问题讨论】:

  • 您确定这些行没有被isComment() 过滤掉吗?请提供Minimal, Complete, and Verifiable Example
  • 好的,我现在就编辑它
  • 你确定isMemLocisComment函数没有错吗?您是否尝试过在调试器中逐行执行代码?
  • 本题本质上是辅助人工阅读的练习。结合冗长的演示文稿,没有努力隔离问题并将自己限制在最小的测试用例和晦涩的标题,我投票关闭它,因为它没有未来价值。

标签: c++ file erase


【解决方案1】:

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

tempLine.erase(0, 1);

然后,你把代码改成了这个(我想是原来的):

tempLine.erase(0);

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

【讨论】:

  • 嘿 LogicStuff,这有点帮助,因为 tempLine.erase(0) 删除了 @ 符号之前的数字 13。我应该用什么来代替 npos?
  • @Barney Chambers 真的之前
  • 因此erase(0,1)call - 我看不到任何东西。你有tempLine.erase(0)。答案中的第一个版本是正确的-我不知道您为什么不明白。
猜你喜欢
  • 2014-09-15
  • 2014-04-06
  • 2013-09-30
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多