C++ Getline to String也会复制换行符
我正在逐行读取文件,并将每一行添加到字符串中。然而,字符串长度每行增加1,我认为这是由于换行符。如何将其从复制中删除 下面是我的代码尝试做同样的事情C++ Getline to String也会复制换行符,c++,string,file-io,newline,C++,String,File Io,Newline,我正在逐行读取文件,并将每一行添加到字符串中。然而,字符串长度每行增加1,我认为这是由于换行符。如何将其从复制中删除 下面是我的代码尝试做同样的事情 if (inputFile.is_open()) { { string currentLine; while (!inputFile.eof()) while( getline( inputFile, currentLine ) ) {
if (inputFile.is_open())
{
{
string currentLine;
while (!inputFile.eof())
while( getline( inputFile, currentLine ) )
{
string s1=currentLine;
cout<<s1.length();
}
if(inputFile.is\u open())
{
{
串电流线;
而(!inputFile.eof())
while(getline(inputFile,currentLine))
{
字符串s1=当前行;
cout看起来,inputFile
具有Windows样式(CRLF),但您的程序在Unix上像换行符(LF)一样拆分输入,因为默认情况下,\n
上的换行符会在字符串的末尾保留CR(\r
)
您需要修剪无关的\r
s。以下是一种方法,以及一个小测试:
#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);
}
注意事项:
- 您不需要测试EOF。将返回流,当它无法从
inputFile
读取更多内容时,流将转换为false
- 不需要复制字符串来确定其长度
这是因为您在MS Windows下,他们在“\n”之前添加了一个“\r”,并且“\r”没有被删除。欢迎使用StackOverflow。我为您格式化了代码。第一个是免费的。之后您必须给我买一品脱;-)std::getline()
丢弃换行符。如何确定预期的行长度?使用COUT这是std::getline()读取的行长度
,这似乎与您期望的不同,可能是不同平台上的换行符问题?文件来自何处,您在哪个平台上编写程序?我使用npp++确定了我逐行选择的内容的长度。因此,它们显示了123450500120,我的程序显示了124451501,120.除最后一行外,all line.length()显示的值增加了1。您是否可以对一个更小的测试文件运行程序,该文件的行长可以手动计算?对于长度为零的行,它会报告什么?(我的报告0)这是不正确的,\r
也会被删除(),但这是一个问题,如果文件存储在Windows下并在Linux下读取。@ChristianAmmer我敢打赌这就是问题所在!当然,当在Windows机器上以文本模式读取文件时,行尾序列会被一个\n
替换,该序列被剥离,但每行末尾的这个漂亮的不可见字符很容易弄乱读取。很容易验证是否是这种情况:如果(!s.empty()&&s.back()='\r'){std::cout@Dietmar:可能对你来说不是,但对我来说这是个问题(Client=Windows,Server=Linux),似乎在OPs的情况下,这才是真正的原因。@Christian实际上,如果你以二进制模式打开文件(这里可能不是这样…)那么在MS Windows下也不会转换\r\n。不过,getline()是否足够聪明,可以完成这项工作,我不是100%确定。
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'