我正在逐行读取文件并将每一行添加到一个字符串中。但是,字符串长度每行增加 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/