简体   繁体   English

在 C++ Builder 6 中使用 ifstream 读取 txt 文件

[英]Reading txt file using ifstream in C++ Builder 6

I'm using C++ BUILDER 6 and I'm trying to understand this code.我正在使用 C++ BUILDER 6,我正在尝试理解这段代码。

I'm logging 4 variables into a txt file and obtaining success:我正在将 4 个变量记录到一个 txt 文件中并获得成功:

sprintf(buffer, "%i,%i,%i,%i", x, yMin, yMed, yMax);
ofstream logData;
logData.open("logData.txt", ios::app);
logData << buffer << "\n";

My txt output:我的txt输出:

1,1686,1784,1972
2,1687,1785,1973
3,1688,1786,1974
...

I need to read this file to get variables back and plot to a graph.我需要阅读这个文件来获取变量并绘制成图形。 I'm doing like this and it's working properly:我正在这样做并且它工作正常:

std::ifstream infile(OpenDialog->FileName.c_str());
int num, y, yMin, yMax;
char a,b,c;
char buffer[100];
if(infile.is_open())
{
    while (infile >> x >> a >> yMin >> b >> yMed >> c >> yMax)
    {
        sprintf(buffer, "X: %i | YMIN: %i | YMED: %i | YMAX: %i", x, yMin, yMed, YMax);
        Memo1->Lines->Add(buffer);
    }
}

My Memo1 output:我的 Memo1 输出:

X:1 | YMIN: 1686 | YMED: 1784 | YMAX: 1972
X:2 | YMIN: 1687 | YMED: 1785 | YMAX: 1973
X:3 | YMIN: 1688 | YMED: 1786 | YMAX: 1974
...

My question is: How did C++ distinguish the variables?我的问题是: C++如何区分变量的? I didn't get where it assumes that x = 1 , yMin = 1686 ... by the while loop reading line by line of txt file:我没有得到它假设x = 1 , yMin = 1686 ... 通过 while 循环逐行读取 txt 文件的地方:

while (infile >> x >> a >> yMin >> b >> yMed >> c >> yMax)

When the code enters to sprinft line:当代码进入 sprint 行时:

sprintf(buffer, "X: %i | YMIN: %i | YMED: %i | YMAX: %i", x, yMin, yMed, YMax);

The variables x, yMin, yMed, YMax already assumed some value from txt file.变量 x、yMin、yMed、YMax 已经从 txt 文件中假定了一些值。

Note: In my understood C++ expects some INT + CHAR + INT + CHAR... Where the CHAR is a ','.注意:在我理解的 C++ 中需要一些 INT + CHAR + INT + CHAR ... 其中 CHAR 是一个“,”。 But '1' is a CHAR too and if I log:但是 '1' 也是一个 CHAR,如果我登录:

1116861178411972 instead 1,1686,1784,1972

It doesn't works properly.它不能正常工作。

Can someone give me some guide?有人可以给我一些指导吗? Somewhere to start to understand it?从哪里开始理解它?

When you do infile >> x and x is an int , the input only reads characters that could be part of an integer value.当您执行infile >> x并且xint ,输入仅读取可能是整数值一部分的字符。 A comma cannot, so the input operation stops there.逗号不能,所以输入操作在那里停止。

Then the input continues with >> a which looks for a single char .然后输入继续>> a寻找单个char A comma is a char, so it is read into a .逗号是一个字符,所以它被读入a .

Then it continues to try to read another integer, and luckily the next part is again digits.然后它继续尝试读取另一个整数,幸运的是下一部分又是数字。

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

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