c++ - 从文件中删除一个以 & 开头然后有 23 个字符的字符串

标签 c++ string file-io

<分区>

我正在开发一个小程序来实现某些目标。

所以我通过使用该程序获得了一个文件,但它有一个字符串在很多地方都以“&”开头。

我将解释我的问题的最小部分。 我有一个字符串,我想在该字符串中删除一些字符,这些字符以“&”开头,后跟 23 位数字。

请建议我如何实现这一目标。

最佳答案

那么,您需要创建一个循环来读取文件中的所有字符串:

std::ifstream fin( "input.txt" );
std::string line;

std::getline( fin, line );
while( !fin.eof() ) {
    getline( fin, line );
}

当然,您不能就地修改文件。您需要将输入文件的内容写入另一个文件。

std::ifstream fin( "input.txt" );
std::ofstream fout( "output.txt" );
std::string line;

std::getline( fin, line );
while( !fin.eof() ) {
    fout << line << std::endl;
    getline( fin, line );
}

唯一剩下的就是定位那些带有'&'的字符串并删除后面的23个字符。

std::ifstream fin( "input.txt" );
std::ofstream fout( "output.txt" );
std::string line;

std::getline( fin, line );
while( !fin.eof() ) {
    unsigned int pos = line.find( '&' );

    if ( pos != string::npos ) {
        string line2 = line.substring( 0, pos -1 );
        line2 += line.substring( pos + 23 );
        line = line2;
    }

    fout << line << std::endl;
    std::getline( fin, line );
}

最后,您需要删除 input.txt。希望这会有所帮助。

关于c++ - 从文件中删除一个以 & 开头然后有 23 个字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8930225/

相关文章:

c++ - 构建和返回复杂结果数据集的有效方法

javascript - 如何在javascript中添加字符串数值?

无法从一组字符串中取出数字 - C

c - 字符串运行时错误仅适用于 getchar 为什么?

c++ - 如何在openGL C++中绘制空心圆

c++ - 与运行时相比,为什么三元运算符在编译时的工作方式不同?

python - 在 Python 中获取目录基名的优雅方法?

java - JTextPane 从文本文件读取

c++ - 如何劫持DLL来锁定Windows中的所有目录来验证

c# - 单元测试文件 I/O