Getline to String复制换行符

typ*_*ef1 3 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();
            }
Run Code Online (Sandbox Code Playgroud)

[更新说明]我使用记事本++来确定我逐行选择的长度.所以他们显示了123,450,500,120,我的节目显示124,451,501,120.除最后一行外,所有line.length()都显示增加1的值.

Joh*_*web 7

它看起来像是inputFileWindows风格的换行符(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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

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'
Run Code Online (Sandbox Code Playgroud)

注意事项:

  • 您无需测试EOF.std::getline()将返回流,false当它不能再读取时将转换为inputFile.
  • 您不需要复制字符串来确定其长度.