简体   繁体   English

使用ifstream的getLine C ++

[英]Using ifstream's getLIne C++

Hello World, 你好,世界,

I am fairly new to C++ and I am trying to read a text file Line by Line. 我是C ++的新手,我想逐行读取文本文件。 I did some research online and stumbled across ifstream. 我在网上做了一些研究,偶然发现了ifstream。

What is troubling me is the getLine Method. 让我困扰的是getLine方法。 The parameters are istream& getline (char* s, streamsize n ); 参数是istream&getline(char * s,streamsize n);

I understand that the variable s is where the line being read is saved. 我知道变量s是读取行的保存位置。 (Correct me if I am wrong) (如果我做错了,请纠正我)

What I do not understand is what the streamsize n is used for. 我不明白的是streamsize n的用途。

The documentation states that: 该文档指出:

Maximum number of characters to write to s (including the terminating null character).

However if I do not know how long a given line is what do I set the streamsize n to be ? 但是,如果我不知道给定行的长度,我应该将streamsize n设置为多少?

Also, 也,

What is the difference between ifstream and istream ? ifstream和istream有什么区别?

Would istream be more suitable to read lines ? istream更适合阅读行吗? Is there a difference in performance ? 性能上有区别吗?

Thanks for your time 谢谢你的时间

You almost never want to use this getline function. 您几乎永远都不想使用此getline函数。 It's a leftover from back before std::string had been defined. 在定义std::string之前,这是一个从后面的剩菜。 It's for reading into a fixed-size buffer, so you'd do something like this: 它用于读取固定大小的缓冲区,因此您将执行以下操作:

static const int N = 1024;
char mybuffer[N];

myfile.getline(mybuffer, N);

...and the N was there to prevent getline from writing into memory past the end of the space you'd allocated. ...那里的N可以防止getline在分配的空间结束后写入内存。

For new code you usually want to use an std::string , and let it expand to accommodate the data being read into it: 对于新代码, 通常需要使用std::string ,并使其扩展以容纳正在读取的数据:

std::string input;

std::getline(myfile, input);

In this case, you don't need to specify the maximum size, because the string can/will expand as needed for the size of the line in the input. 在这种情况下,您无需指定最大大小,因为字符串可以/将根据需要扩展为输入中行的大小。 Warning: in a few cases, this can be a problem--if (for example) you're reading data being fed into a web site, it could be a way for an attacker to stage a DoS attack by feeding an immense string, and bringing your system to its knees trying to allocate excessive memory. 警告:在某些情况下,这可能是个问题-例如(如果您正在读取正在馈入网站的数据),这可能是攻击者通过馈入巨大的字符串进行DoS攻击的一种方式,并使您的系统瘫痪,试图分配过多的内存。

Between istream and ifstream: an istream is mostly a base class that defines an interface that can be used to work with various derived classes (including ifstream objects). 在istream和ifstream之间:istream主要是基类,它定义可用于与各种派生类(包括ifstream对象)一起使用的接口。 When/if you want to open a file from disk (or something similar) you want to use an ifstream object. 当/如果您想从磁盘(或类似的东西)打开文件,您想使用一个ifstream对象。

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

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