简体   繁体   English

如何使用ifstream c ++从带有换行符的文件中读取字符串?

[英]How to read string from file with line break using ifstream c++?

I used this code to read lines from file, but I noticed, that it didn't read line breaks: 我使用以下代码从文件读取行,但是我注意到,它没有读取换行符:

ifstream fs8(sourceFile);
string line;

while (getline(fs8, line))
{
   //here I am doing convertation from utf8 to utf16, but I need also to convert symbol "\n"
}

How to read line with line breaks ? 如何用换行符读取换行符?

std::getline() reads data up to a delimiter, which is not stored. std::getline()读取数据直至不存储分隔符。 By default, that delimiter is '\\n' . 默认情况下,该分隔符为'\\n' So you would have to either: 因此,您必须:

a) Pick a different delimiter -- but then you would no longer read "lines". a)选择一个不同的定界符-但是您将不再阅读“行”。

b) Add the newline to the data read ( line += '\\n' ). b)将换行符添加到读取的数据中( line += '\\n' )。

I'd go for b), if you really need that newline converted. 如果您确实需要换行符,我会选择b)。 (I don't quite see why that would be necessary, but who am I to judge. ;-) ) (我不太明白为什么这样做是必要的,但是我要判断谁。;-))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM