-2

I'm using C++ BUILDER 6 and I'm trying to understand this code.

I'm logging 4 variables into a txt file and obtaining success:

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

My txt output:

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:

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? I didn't get where it assumes that x = 1, yMin = 1686 ... by the while loop reading line by line of txt file:

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

When the code enters to sprinft line:

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.

Note: In my understood C++ expects some INT + CHAR + INT + CHAR... Where the CHAR is a ','. But '1' is a CHAR too and if I log:

1116861178411972 instead 1,1686,1784,1972

It doesn't works properly.

Can someone give me some guide? Somewhere to start to understand it?

dsicari
  • 590
  • 6
  • 13
  • Possible duplicate of [How does the particular C function work?](https://stackoverflow.com/questions/8883896/how-does-the-particular-c-function-work) – underscore_d Oct 26 '17 at 13:56
  • For starters: http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2 – user0042 Oct 26 '17 at 13:57
  • 1
    You should explain which specific bit you don't understand. `cin`, `printf`, or something else? – underscore_d Oct 26 '17 at 13:59
  • C++ Builder's standard support is fairly bad - only up to C++11. Use anything else if at all possible - recent versions of GCC, MSVC and Clang are much better (even Intel C++ would be better - and that's quite bad!). – tambre Oct 26 '17 at 14:11

1 Answers1

1

When you do infile >> x and x is an int, the input only reads characters that could be part of an integer value. A comma cannot, so the input operation stops there.

Then the input continues with >> a which looks for a single char. A comma is a char, so it is read into a.

Then it continues to try to read another integer, and luckily the next part is again digits.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203