Getline to String复制换行符

时间:2012-01-22 09:01:55

标签: 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的值。

2 个答案:

答案 0 :(得分:7)

看起来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()将返回该流,当false不再读取时,该流将转换为inputFile
  • 您无需复制字符串即可确定其长度。

答案 1 :(得分:1)

那是因为你在MS-Windows下,他们在“\ n”之前添加了一个“\ r”,并且“\ r”没有删除。