c++在Unix编译器上清除字符串中的Windows新行元素

C++ Scrubbing Windows New Line Elements in a String on a Unix Compiler

本文关键字:Windows 新行 元素 字符串 清除 Unix 编译器 c++      更新时间:2023-10-16

我正在使用Unix shell编译器,需要导入一个Windows .dat文件进行输入。不幸的是,这意味着在输入文件中存在用于回车的本地'rn'组件。

我希望用下面一行的东西来清除这些:

#include <fstream>
#include <string>
using namespace std;
int main()
{
    ifstream inputFile;
    inputFile.open("myFile.dat");
    string array[100];
    int i = 0;
    while(getline(dataIn, str))
    {
        str.erase(remove(str.begin(), str.end(), 'n'), str.end());
        str.erase(remove(str.begin(), str.end(), 'r'), str.end());
        array[0] = str;
        i++;
    }
    return 1;
}

但是,这会提供以下错误:

error: cannot convert ‘__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >’ to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)’

表示第一个erase(),后面跟着

error: request for member ‘erase’ in ‘temp.std::basic_string<_CharT, _Traits, _Alloc>::c_str [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]()’, which is of non-class type ‘const char*’

我已经尝试了str.c_str().erase,但这导致了第二个错误的重复。

代码中的两个问题:

  1. 如果要使用remove算法功能,需要增加#include <algorithm>
  2. 要确保::remove(这是一个删除由char *参数命名的文件的函数)没有被拾取,使用std::remove