简体   繁体   English

在C ++中读取文本文件

[英]read text file in C++

I have a question regarding what to do with "\\n" or "\\r\\n" etc. when reading a text file in C++. 我在使用C ++读取文本文件时遇到有关如何处理"\\n""\\r\\n"等问题。 The problem exists when I do the following sequence of operations: 当我执行以下操作序列时,存在问题:

int k;
f>>k;
string line;
getline(f,line);

for an input file with something like 对于具有类似内容的输入文件

1
abc

I have to put a f.get() in order to read off the ending "\\n" after f>>k . 我必须放入f.get()以便在f>>k之后读取结尾的"\\n" I even have to do f.get() twice if I have "\\r\\n" . 如果我有"\\r\\n"我甚至必须做两次f.get()

What is an elegant way of reading file like this if I mix >> with getline ? 如果我将>>getline混合使用,那么读取文件的优雅方式是什么?

Thank you. 谢谢。

Edit Also, I wonder if there is any convenient way to automatically detect the given file has an end-of-line char "\\n" or "\\r\\n" . 编辑另外,我想知道是否有任何方便的方法来自动检测给定文件的行尾字符为"\\n""\\r\\n"

You need to fiddle a little bit to >> and getline to work happily together. 您需要花一点时间去>>getline一起快乐地工作。 In general, reading something from a stream with the >> operator will not discard any following whitspaces (new line characters). 通常,使用>>运算符从流中读取内容不会丢弃任何后续的空格(换行符)。

The usual approach to solve this is with the istream::ignore function following >> - telling it to discard every character up to and including the next newline. 解决此问题的常用方法是使用>>istream::ignore函数-告诉它丢弃直到下一个换行符的所有字符。 (Only useful if you actually want to discard every character up to the newline though). (仅在您实际上要舍弃换行符之前的每个字符时才有用)。

eg 例如

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int n;
    std::string s;
    std::cout << "type a number: ";
    std::cin >> n;
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    std::cout << "type a string: ";
    std::getline( std::cin, s );
    std::cout << s << " " << n << std::endl;
}

edit (I realise you mentioned files in the question, but hopefully it goes without saying that std::cin is completely interchangable with an ifstream) 编辑 (我意识到您在问题中提到了文件,但希望它不用说std :: cin与ifstream完全可互换)

完全不同的方法是使用tr预处理数据文件(假设您使用Linux)删除\\r ,然后使用getline()

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

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