Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Результат_2012_02_09.docx
Скачиваний:
6
Добавлен:
20.04.2015
Размер:
593.36 Кб
Скачать

Задача 4. Удалить все нечетные элементы из массива (основа тестов)

Теперь составим тесты для данной задачи.

  1. Для того, что бы легче было писать тесты, необходимима функция ввода, которая заполняет вектор числами, введенными с клавиатуры, а не случайными. Поэтому добавим функцию, которая выполняет эту задачу.

void handFillVector(vector<int> &data, int size) {

data.reserve(size);

for (int i = 0; i < size; i++) {

data.push_back(getCorrectValue());

}

}

  1. Заменим вызов функции заполнения вектора случайными числами на «ручной» ввод и вынесем в отдельную функцию.

void makeLab() {

cout << "enter array size: ";

int size = getCorrectValue();

if (size < 0) {

cout << "array size can not be negative number";

_getch();

return;

}

vector<int> data;

handFillVector(data, size);

printVector("before process", data);

mainAction(data);

printVector("after process", data);

}

  1. Следует отметить, что в С++ можно перенаправлять стандартный поток ввода на ввод из файла, а стандартный поток вывода – на вывод в файл. Поэтому добавим функцию, которая принимает имя входного и выходного файла и перенаправляет потоки в них. Отметим, что необходимо подключить модуль #include <fstream>.

void redirectStreams(string infileName, string outFileName) {

streambuf *oldInput = cin.rdbuf();

streambuf *oldOutput = cout.rdbuf();

ifstream ifs(infileName.c_str());

ofstream ofs(outFileName.c_str());

cin.rdbuf(ifs.rdbuf());

cout.rdbuf(ofs.rdbuf());

makeLab();

ifs.close();

ofs.close();

cin.rdbuf(oldInput);

cout.rdbuf(oldOutput);

}

  1. Приведем полный код программы

#include <vector>

#include <time.h>

#include <conio.h>

#include <list>

#include <iostream>

#include <fstream>

#include <algorithm>

#include <strstream>

using namespace std;

bool isOdd(int s) {

return s % 2 == 1;

}

void mainAction(vector<int> &data) {

vector<int>::iterator newEnd = remove_if(data.begin(),data.end(), isOdd);

data.erase(newEnd, data.end());

}

int getCorrectValue() {

while (true) {

int size;

if (!(cin >> size)) {

cin.clear();

while(std::cin.get()!= '\n');

continue;

}

return size;

}

}

void printVector(char *caption, vector<int> &data) {

cout << caption << ": ";

for (vector<int>::iterator i = data.begin(); i != data.end(); ++i) {

cout << *i << " ";

}

cout << "\n";

}

void handFillVector(vector<int> &data, int size) {

data.reserve(size);

for (int i = 0; i < size; i++) {

data.push_back(getCorrectValue());

}

}

void makeLab() {

cout << "enter array size: ";

int size = getCorrectValue();

if (size < 0) {

cout << "array size can not be negative number";

_getch();

return;

}

vector<int> data;

handFillVector(data, size);

printVector("before process", data);

mainAction(data);

printVector("after process", data);

}

void redirectStreams(string infileName, string outFileName) {

streambuf *oldInput = cin.rdbuf();

streambuf *oldOutput = cout.rdbuf();

ifstream ifs(infileName.c_str());

ofstream ofs(outFileName.c_str());

cin.rdbuf(ifs.rdbuf());

cout.rdbuf(ofs.rdbuf());

makeLab();

ifs.close();

ofs.close();

cin.rdbuf(oldInput);

cout.rdbuf(oldOutput);

}

int main(int argc, char* argv[]) {

redirectStreams("labin.txt", "labout.txt");

return 0;

}

  1. Теперь необходимо вызвать эту функцию с передачей входного файла (содержимое которого для этой задачи может быть «5 1 2 3 4 5»), и сравнить содержимое выходного файла с эталонным выходным файлом. Задача для чтения всего содержимого файла уже рассматривалась. Задача составления тестов так же рассматривалась, поэтому не будем приводить здесь рассуждения.