例如,我有一个包含以下内容的文件:
Hello John Smith
Hello Jack Brown
OK I love you
请注意,每个句子都有一些前导空格。我想使用 std::fstream
逐行读取它们,并希望删除前导空格但保留句子中单词之间的空格。
我想要的输出应该如下:
Hello John Smith
Hello Jack Brown
OK I love you
我还找到了 this post为我的问题提供了许多简单的方法。但是,我认为就现代 C++ 而言,它们都不是优雅的。有没有更优雅的手段?
最佳答案
std::ifstream file("input.txt");
std::string line;
while(std::getline(file,line))
{
auto isspace = [](unsigned char ch) { return std::isspace(ch); };
//find the first non-space character
auto it = std::find_if_not(line.begin(), line.end(), isspace);
line.erase(line.begin(), it); //erase all till the first non-space
std::cout << line << "\n";
}
请注意,我们可以将 std::isspace
作为第三个参数传递给 std::find_if_not
,但是有 overloads of std::isspace
这会导致编译错误——要解决此问题,您可以使用 cast,如:
auto it = std::find_if_not(line.begin(),
line.end(),
static_cast<int(*)(int)>(std::isspace));
看起来很丑。但是由于转换中的函数类型,编译器能够计算出 which overload您打算在代码中使用。
关于c++ - 如何删除前导空格但保留 C++ `ifstream` 中的中间空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513312/