c++ - Getline to String 也复制换行符

标签 c++ string file-io newline

我正在逐行读取文件并将每一行添加到一个字符串中。但是,字符串长度每行增加 1,我认为这是由于换行符引起的。我怎样才能将它从被复制中删除。

这是我尝试执行相同操作的代码。

if (inputFile.is_open())
{
    {
        string currentLine;
        while (!inputFile.eof())
            while( getline( inputFile, currentLine ) )
            {
                string s1=currentLine;
                cout<<s1.length();
            }

[更新说明] 我已经使用 notepad++ 来确定我逐行选择的内容的长度。所以他们显示了一些 123、450、500、120,而我的程序显示了 124,451,501,120。除了最后一行,所有 line.length() 都显示增加了 1 的值。

最佳答案

看起来 inputFile 具有 Windows 风格 line-breaks (CRLF) 但是你的程序在类似 Unix 的换行符 (LF) 上拆分输入,因为 std::getline() , 默认情况下在 \n 处中断,将 CR (\r) 留在字符串的末尾。

您需要修剪无关的 \r。下面是一种方法,以及一个小测试:

#include <iostream>
#include <sstream>
#include <iomanip>

void remove_carriage_return(std::string& line)
{
    if (*line.rbegin() == '\r')
    {
        line.erase(line.length() - 1);
    }
}

void find_line_lengths(std::istream& inputFile, std::ostream& output)
{
    std::string currentLine;
    while (std::getline(inputFile, currentLine))
    {
        remove_carriage_return(currentLine);
        output
            << "The current line is "
            << currentLine.length()
            << " characters long and ends with '0x"
            << std::setw(2) << std::setfill('0') << std::hex
            << static_cast<int>(*currentLine.rbegin())
            << "'"
            << std::endl;
    }
}

int main()
{
    std::istringstream test_data(
        "\n"
        "1\n"
        "12\n"
        "123\n"
        "\r\n"
        "1\r\n"
        "12\r\n"
        "123\r\n"
        );

    find_line_lengths(test_data, std::cout);
}

输出:

The current line is 0 characters long and ends with '0x00'
The current line is 1 characters long and ends with '0x31'
The current line is 2 characters long and ends with '0x32'
The current line is 3 characters long and ends with '0x33'
The current line is 0 characters long and ends with '0x00'
The current line is 1 characters long and ends with '0x31'
The current line is 2 characters long and ends with '0x32'
The current line is 3 characters long and ends with '0x33'

注意事项:

  • 您不需要测试 EOF。 std::getline()将返回流,当它无法从 inputFile 中读取更多内容时,它将转换为 false
  • 您不需要复制字符串来确定其长度。

关于c++ - Getline to String 也复制换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960055/

相关文章:

c++ - Qt 主窗口关闭后如何返回信息?

c# 将字符串作为代码执行...值得付出努力吗?

bash - 检查文件是否存在

c - 我如何判断文件是否在 Linux 的 C 中的其他地方打开?

file-io - 在 Julia 1.0.0 中将大型数字输出保存到 native 文件

c++ - 从 C 库调用 C++ 函数指针

c++ - 有什么理由在 C++03 中使用 'auto' 关键字吗?

c++ - boost asio 需要在 m 个工作完成后才发布 n 个工作

c# - 使用 InvariantCultureIgnoreCase 而不是 ToUpper 进行不区分大小写的字符串比较

android - 字符串上出现奇怪的 NullPointerException