0

I'm trying to take input from a text file to call a function. The function takes 3 int paramaters. Each line in the text file will include each int followed by a space. How do I parse each line, call a function using integers from each line, and then exit the loop and close the file? Any help would be greatly appreciated.

// Here is what the contents of the text file will look like
1 2 3
4 5 6 
7 8 9
10 11 12

// here is the function
void readValues(int1, int2, int3)
{
    // do something
}

// open text file and parse input. if it does not exist, create file

ifstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

while (file.eof())
{

    int a, b, c;
    file >> a >> b >> c >> std::endl;
    readValues(a, b, c); // first iteration would be readValues(1, 2, 3)

    if(file.eof())
    {
         break;
    }
}

file.close();
user3781214
  • 357
  • 1
  • 3
  • 16

1 Answers1

1

If you're going to read a file, you shouldn't also open it for writing (fstream::out) and truncate it (fstream::trunc).

You also shouldn't test for eof in your loop condition — there are a few occasions when eof is appropriate, but you won't encounter any for your first few years of C++ programming.

And you don't need to explicitly close the file, the destructor handles that.

Do it like this:

int main()
{
    ifstream file("test.txt");

    int a, b, c;

    while (file >> a >> b >> c)
    {
        readValues(a, b, c);
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82