特别是我对 istream& getline ( istream& is, string& str );
感兴趣。Ifstream 构造函数是否有一个选项来告诉它将所有换行编码转换为“ n”?我希望能够调用 getline
,并让它优雅地处理所有行结束。
更新 : 为了澄清,我希望能够编写几乎可以在任何地方编译的代码,并且几乎可以在任何地方接受输入。包括有 r 没有 n 的罕见文件。最大限度地减少软件用户的不便。
解决这个问题很容易,但我仍然很好奇在标准中如何灵活地处理所有文本文件格式。
getline
以整行的形式读入一个字符串,直到“ n”为止。N’是从流中使用的,但 getline 没有将它包含在字符串中。到目前为止还可以,但是在字符串中包含的 n 之前可能有一个“ r”。
在文本文件中可以看到 三种线尾: N’是 Unix 机器上的常规结尾,r’(我认为)用于旧的 Mac 操作系统,而 Windows 使用一对,r’后跟 n’。
问题是 getline
把’r’放在字符串的末尾。
ifstream f("a_text_file_of_unknown_origin");
string line;
getline(f, line);
if(!f.fail()) { // a non-empty line was read
// BUT, there might be an '\r' at the end now.
}
谢谢尼尔指出 f.good()
不是我想要的,!f.fail()
才是我想要的。
我可以手动删除它自己(见这个问题的编辑) ,这是很容易的 Windows 文本文件。但我担心有人会输入一个只包含 r 的文件。在这种情况下,我假设 getline 将消耗整个文件,并认为它只是一行!
. . 而且这还不包括 Unicode: -)
. . 也许 Boost 有一个不错的方法,可以从任何文本文件类型一次消耗一行?
编辑 我正在使用这个来处理 Windows 文件,但我仍然觉得我不应该这样做!而且这个不会转移到只有 r’的文件。
if(!line.empty() && *line.rbegin() == '\r') {
line.erase( line.length()-1, 1);
}