Ввод символов из текстового файла 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Ввод символов из текстового файла



#include <fstream>

#include <iostream>

using namespace std;

 

int main()

{

char ch;

ifstream infile ("TEST.TXT"); //открытие потока для ввода

while(infile) //ввод до EOF или ошибки

{

infile. get(ch); //ввод символа

cout << ch; //вывод символа

}

cout << endl;

_getch();

return 0; //при завершении программы файл будет закрыт

}

////////////////////////////////////////////////////////////////

 

Вывод строк в текстовый файл

#include <fstream>

using namespace std;

 

int main()

{

ofstream outfile ("TEST.TXT"); // открытие потока для вывода

//вывод в файл

outfile << "I fear thee, ancient Mariner! \n ";

outfile << "I fear thy skinny hand \n ";

outfile << "And thou art long, and lank, and brown," << endl;

outfile << "As is the ribbed sea sand." << endl;

cout << "File written\n";

_getch();

return 0; //при завершении программы файл будет закрыт

}

////////////////////////////////////////////////////////////////

Ввод из текстового файла строк

#include <fstream>

#include <iostream>

using namespace std;

 

int main()

{

const int MAX = 80; //размер буфера

char buffer[MAX]; //буфер

ifstream infile ("TEST.TXT"); // открытие потока для ввода

while(!infile.eof ()) //пока не конец файла

{

infile.getline (buffer, MAX); //читать строку из файла

cout << buffer << endl; //вывести строку

}

_getch();

return 0; //при завершении программы файл будет закрыт

}

 

////////////////////////////////////////////////////////////////

Чтение и вывод на экран буфера текстового файла

#include <fstream>

#include <iostream>

using namespace std;

 

int main()

{

ifstream infile ("TEST.TXT"); // открытие потока для ввода

 

cout << infile.rdbuf (); //вывод буфера на экран

cout << endl;

_getch();

return 0; //при завершении программы файл будет закрыт

}

 

////////////////////////////////////////////////////////////////

Пример использования функций, текстовых файлов и многофайловой компиляции

1. Описать структуру с именем STUDENT, содержащую следующие поля:

· NAME – фамилия и инициалы;

· номер группы;

· успеваемость (массив из пяти элементов).

2. Написать программу, выполняющую следующие действия:

· вывод десяти структур данных типа STUDENT с клавиатуры в файл;

· чтение из файла и вывод на дисплей фамилий и номеров групп для всех студентов, имеющих хотя бы одну оценку 3;

· если таких студентов нет, вывести соответствующее сообщение.

////////////////////////////////////////////////////////////////

 

//head.h константы, определение структурного типа, прототипы функций

const int KOL_ST = 10;

const int KOL_OC = 5;

const int BAL = 3;

struct student {

unsigned short gruppa;

char fio[20];

unsigned short ysp[KOL_OC];

};

 

int vivod_file_txt (char [],const int, const int);

int vvod_file_txt (char[],const int, const int);

int otsenka (unsigned short [],const int,const int);

////////////////////////////////////////////////////////////////

// stdafx.h

#pragma once

 

#define WIN32_LEAN_AND_MEAN// Exclude rarely-used stuff from Windows headers

#include <stdio.h>

#include <tchar.h>

 

// TODO: reference additional headers your program requires here

#include <iostream>

#include <fstream>

#include <iomanip>

#include <conio.h>

#include "head.h"

using namespace std;

////////////////////////////////////////////////////////////////

//func.cpp

#include "stdafx.h"

int vivod_file_txt (char name_file[],const int kol_st,
const int kol_oc)

{

ofstream outfile (name_file);

if (!outfile) {

cout <<"error ofstream"<<endl;

_getch();

return 1;

}

student stud; //определение структуры

for (int i=0; i<kol_st; i++) { //заполнение полей структуры

cout <<"vvedite fio studenta #"<<i+1<<" ";

cin >>stud.fio; //чтение поля структуры с клавиатуры

outfile << stud.fio <<' \n '; //запись поля структуры в файл

 

cout << "vvedite gryppy studenta #"<<i+1<<" ";

cin >> stud.gruppa;

outfile << stud.gruppa <<' \n ';

 

cout <<"vvedite otsenki studenta #"<<i+1<<endl;

for (int j=0; j<kol_oc; j++)

{cin >>stud.ysp[j];

outfile << stud.ysp[j] <<' \n ';

}

 

}

cout << "file is made \n" << endl;

outfile.close();

return 0;

}

 

//предполагаем, что если из файла считывается строка с фамилией
// студента, то считается и последующая информация о нем.

int vvod_file_txt (char name_file[],const int kol_oc, const int bal) {

bool prov = false;

ifstream infile (name_file);

if(!infile) {

cout<<"error ifstream"<< endl;

_getch();

return 1;

}

student stud;

while (true) {

infile >> stud.fio;

if (infile.eof()) break; //проверка по stud.fio на конец файла

infile >> stud. gruppa;

for (int j=0; j<kol_oc; j++)

infile >>stud.ysp[j];

if (otsenka(stud.ysp,kol_oc,bal)) {

prov = true;

cout << "student " << setw(15) << stud.fio

<< " iz " << stud.gruppa

<< "-y gruppi imeet hotya bi odny troiky" << endl;

}

}

 

if (!prov) cout << "net studentov, imeyuschih troiki" << endl;

infile.close ();

return 0;

 

}

int otsenka (unsigned short ysp[],const int kol_oc, const int bal) {

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

if (ysp[i]==bal) return 1;

}

return 0;

}

 

////////////////////////////////////////////////////////////////

//main.cpp

 

#include "stdafx.h"

int main () {

char name_file[20]; //имя файла

 

cout <<"vvedite imya faila: ";

cin.getline (name_file,20);

 

if (vivod_file_txt ( name_file,KOL_ST,KOL_OC ))

{cout <<"error vivod_file_txt() "<<endl;

_getch();

return 1;

}

else if (vvod_file_txt ( name_file,KOL_OC, BAL ))

{ cout <<"error vvod_file_txt() "<<endl;

_getch();

return 2;

}

else

_getch();

return 0;

}

 

////////////////////////////////////////////////////////////////

Ввод-вывод в двоичный файл

 

#include <fstream>

#include <iostream>

using namespace std;

const int MAX = 100; //размер буфера

int buff[MAX]; //буфер для данных

 

int main()

{

for(int j=0; j<MAX; j++) //заполнение буфера данных

buff[j] = j; //(0, 1, 2,...)

// создание потока вывода

ofstream os ("edata.dat", ios::binary);

//вывод из буфера в поток

os.write(reinterpret_cast<char*>(buff), MAX*sizeof(int));

os.close(); //закрыть поток

 

for(int j=0; j<MAX; j++) //очистка буфера

buff[j] = 0;

//создание потока ввода

ifstream is ("edata.dat", ios::binary);

//чтение из потока в буфер

is.read(reinterpret_cast<char*>(buff), MAX*sizeof(int));

 

for(int j=0; j<MAX; j++) //проверка данных

if(buff[j]!= j)

{ cerr << "Data is incorrect\n"; return 1; }

cout << "Data is correct\n";

_getch();

return 0; //при завершении программы файл будет закрыт

}

 

////////////////////////////////////////////////////////////////

Пример использования функций, бинарных файлов и многофайловой компиляции

1. Описать структуру с именем STUDENT, содержащую следующие поля:

· NAME – фамилия и инициалы;

· номер группы;

· успеваемость (массив из пяти элементов).

2. Написать программу, выполняющую следующие действия:

· ввод десяти структур данных типа STUDENT с клавиатуры в файл;

· вывод на дисплей фамилий и номеров групп для всех студентов, имеющих хотя бы одну оценку 3;

· если таких студентов нет, вывести соответствующее сообщение.

////////////////////////////////////////////////////////////////

//head.h

 

const int KOL_ST = 10;

const int KOL_OC = 5;

const int BAL = 3;

 

struct student {

unsigned short gruppa;

char fio[20];

unsigned short ysp[KOL_OC];

};

 

int vivod_file (char [],const int, const int);

int vvod_file (char[],const int, const int);

int otsenka (unsigned short [],const int,const int);

////////////////////////////////////////////////////////////////

// stdafx.h

#pragma once

 

#define WIN32_LEAN_AND_MEA// Exclude rarely-used stuff from Windows headers

#include <stdio.h>

#include <tchar.h>

 

// TODO: reference additional headers your program requires here

#include <iostream>

#include <fstream>

#include <iomanip>

#include <conio.h>

#include "head.h"

using namespace std;

////////////////////////////////////////////////////////////////

//func.cpp

#include "stdafx.h"

int vivod_file (char name_file[],const int kol_st,const int kol_oc) {

 

ofstream file (name_file,ios::binary|ios::out);

if (!file) {

cout <<"error ofstream"<<endl;

_getch();

return 1;

}

student stud; //определение структуры

for (int i=0; i<kol_st; i++) {//цикл заполнения полей структуры

cout <<"vvedite fio studenta #"<<i+1<<" ";

cin >>stud.fio;

cout <<"vvedite gryppy studenta #"<<i+1<<" ";

cin >>stud.gruppa;

cout <<"vvedite otsenki studenta #"<<i+1<<endl;

for (int j=0; j<kol_oc; j++)

cin >>stud.ysp[j];

file.write (reinterpret_cast< char* >(&stud), sizeof (student));

//вывод в файл заполненной структуры

}

cout << "file is made \n" << endl;

file.close();

return 0;

}

 

int vvod_file (char name_file[],const int kol_oc, const int bal) {

bool prov = false;

ifstream file (name_file,ios::binary|ios::in);

if(!file) {

cout<<"error ifstream"<< endl;

_getch();

return 1;

}

student stud;

while (true) {

file.read (reinterpret_cast< char* > (&stud), sizeof (student));

if (file.eof()) break;

if (otsenka(stud.ysp,kol_oc,bal)) {

prov = true;

cout << "student " << setw(15) << stud.fio

<< " iz " << stud.gruppa

<< "-y gruppi imeet hotya bi odny troiky" << endl;

}

}

if (!prov) cout << "net studentov, imeyuschih troiki" << endl;

return 0;

}

int otsenka (unsigned short ysp[],const int kol_oc, const int bal) {

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

if (ysp[i]==bal) return 1;

}

return 0;

}

////////////////////////////////////////////////////////////////

//main.cpp

 

#include "stdafx.h"

 

int main () {

char name_file[20]; //имя файла

 

cout <<"vvedite imya faila: ";

cin.getline (name_file,20);

if (vivod_file ( name_file,KOL_ST,KOL_OC ))

{cout <<"error vivod_file() "<<endl;

_getch();

return 1;

}

else if (vvod_file ( name_file,KOL_OC, BAL ))

{ cout <<"error vvod_file() "<<endl;

_getch();

return 2;

}

else

_getch();

return 0;

 

}

////////////////////////////////////////////////////////////////

 

Аргументы командной строки

using namespace std;

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

{

cout << "\nargc = " << argc << endl; //количество аргументов

 

for(int j=0; j<argc; j++) //вывод аргументов

cout << "Argument " << j << " = " << argv[j] << endl;

return 0;

}

////////////////////////////////////////////////////////////////

Задание параметров программы в командной строке

Задание аргумента при выполнении программы в среде MS Visual C++ 2005 осуществляется следующим образом:

· вокне Solution Explorer выделить проект (щелкнуть на названии проекта)à

· в меню Project àвыбрать команду Properties à

· в открывшемся окне Property Pages выбрать команду Debugging à

· в появившейся таблице в поле Command Arguments ввести строку аргументовдля программы.

 

 

//в программе в качестве аргумента функции main() задается путь
// к текстовому файлу

//в командной строке задано proba.txt (для файла из текущей папки)

#include <iostream>

#include <conio.h>

using namespace std;

 

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

{

if (!(argc >=2))

{

cout<<"arguments? \n";

_getch();

return 1;

}

 

ifstream fp(argv[1]);

cout<<"+++++++++++++++++++++++++++++++++++++++++++++\n";

cout<<argv[1]<<endl;

cout<<"+++++++++++++++++++++++++++++++++++++++++++++\n";

 

if (!fp)

{

cout<<"error of open file";

_getch();

return 1;

}

......

}

 

////////////////////////////////////////////////////////////////



Поделиться:


Последнее изменение этой страницы: 2016-12-17; просмотров: 154; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.137.172.68 (0.093 с.)