简体   繁体   English

C ++逐行从文件读取数据

[英]C++ Reading data from a file line by line

I am new to programming and I have this question. 我是编程新手,所以有这个问题。 I have this file that I am opening 我有我要打开的文件

ifstream fin;
FILE * pFile;
pFile = fopen (fname,"r");

The file has 3 data each line. 该文件每行有3个数据。 The first is an integer, the second is an alphabet and the third is an address(like computer memory address). 第一个是整数,第二个是字母,第三个是地址(如计算机内存地址)。 How do I extract these line by line into 3 variables that I can process, and then repeat it with next line and so. 如何将这些行逐行提取到我可以处理的3个变量中,然后在下一行重复该过程,依此类推。

You should know that there are preferred C++ methods for manipulation of files over C stdio methods: 您应该知道,与C stdio方法相比,还有一些首选的C ++方法来处理文件:

  • Using standard predefined streams: std::ofstream for output and std::ifstream for input. 使用标准的预定义流: std::ofstream用于输出, std::ifstream用于输入。
  • Formatted/Unformatted I/O such as operator<<() , operator>>() , read() and write() . 格式化/未格式化的I / O,例如operator<<()operator>>()read()write()
  • In-memory I/O for manipulation of extracted data. 内存中的I / O,用于处理提取的数据。

What you need for this particular case is input stream functionality along with formatted input. 对于这种特殊情况,您需要输入流功能以及格式化的输入。 The formatted input will be done through operator>>() . 格式化的输入将通过operator>>()

But before you get to that, you have to instantiate a file stream. 但是在开始之前,您必须实例化文件流。 Since you're using input, std::ifstream will be used: 由于您正在使用输入,因此将使用std::ifstream

std::ifstream in("your/path.txt");

The next thing to do is to create the three variables whose values you will extract into the stream. 接下来要做的是创建三个变量,将其值提取到流中。 Since you know the types beforehand, the types you will need is an integer, character, and string respectively: 由于您事先知道类型,因此所需的类型分别是整数,字符和字符串:

int  num;
char letter;
std::string address;

The next thing to do is to use operator>>() to obtain the first valid value from the stream. 下一步是使用operator>>()从流中获取第一个有效值。 The way it works is that the function analyses the type of the righthand operand and determines if the characters extracted from the file stream will create a valid value after parsing. 它的工作方式是该函数分析右操作数的类型,并确定从文件流中提取的字符在解析后是否会创建有效值。 When the stream hits whitespace, the new line character or the EOF (end-of-file) character (or a character that doesn't match that of the operand's type), extraction will stop. 当流到达空格,换行符或EOF(文件结尾)字符(或与操作数类型不匹配的字符)时,提取将停止。

What makes IOStreams powerful is that it allows chaining of expressions. 使IOStreams强大的原因是它允许表达式的链接。 So you are able to do this: 因此,您可以执行以下操作:

in >> num >> letter >> address;

which is equivalent to: 等效于:

in >> num;
in >> letter;
in >> address;

This is all that is needed for this simple case. 这是此简单案例所需的全部内容。 In more complex situations, loops and in-memory I/O might be needed for successful extractions. 在更复杂的情况下,成功提取可能需要循环和内存I / O。

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

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