Name: _______KEY________

 

Quiz 7 (Week 8)

CS-150, Fall ‘02, Dr. C. S. Tritt

 

Each of the following 2 questions is worth the same amount.

 

1.      What output would the following fragment of C++ code and associated data file produce (assume any necessary header files have been included and variables declared and defined)?

 

File MyInput.dat –

 

1 2

3 4

5 6

 

Source fragment –

 

ifstream fin("MyInput.dat");

int a, b;

fin >> a >> b;

while (fin)

{

      cout << "The values were: " << a << " and “ << b << endl;

      fin >> a >> b;

}

if (fin.eof())

cout << "Got there.\n";

      else

            cout << "Didn’t get there.\n";

 

Answer –

 

The values were: 1 and 2

The values were: 3 and 4

The values were: 5 and 6

Got there.

 

Noticing missing semicolons on original test + 5 bonus, treating got there as in loop –15, not repeating The values were… -15, displaying Didn’t get there –10,

 

2.      Write a fragment of C++ code that creates a file stream for input, associates it with the file “SomeStuff.dat” and writes a table of integers from 1 to 5 and their squares to it. The exact appearance of the output file is not critical but a possible output file is shown below.

1 1

2 4

3 9

4 16

5 25

 

Answer –

 

   ofstream fout("SomeStuff.dat");

   for (int i = 1; i <= 5; i++) fout << i << ' ' << i*i << endl;

   fout.close();

 

Not incrementing x -10, not looping correctly –10,