Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
34 / 10 / 2
Регистрация: 20.02.2016
Сообщений: 1,560
1

Почему не работает код при переходе на fstream?

26.10.2018, 23:20. Показов 933. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго времени суток!
Ломаю, по незнанию, голову над следующим вопросом. Ниже такой код (из книги Лафоре ): объект записывает/читает записанную в файл информацию (имя/возраст). Прописываются объекты классов ofstream/ifstream. И ещё подсчитывается количество записанных в файл людей.
Я не знаю почему, если я пропишу один объект класса fstream, программа не работает. Данные записываются, но когда нужно
их прочитать данные не выводятся нормально. Вместо заданного количества записей чтение и вывод данных на экран происходят бесконечно. То есть ошибка где-то на этапе подсчёта количества записанных персон, строка 35.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <fstream>               //for file streams
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class person                     //class of persons
   {
   protected:
      char name[40];             //person's name
      int age;                   //person's age
   public:
      void getData(void)         //get person's data
         {
         cout << "\n   Enter last name: "; cin >> name;
         cout << "   Enter age: "; cin >> age;
         }
      void showData(void)        //display person's data
         {
         cout << "\n   Name: " << name;
         cout << "\n   Age: " << age;
         }
      void diskIn(int);          //read from file
      void diskOut();            //write to file
      static int diskCount();    //return number of
                                 //   persons in file
   };
//--------------------------------------------------------------
void person::diskIn(int pn)      //read person number pn
   {                             //from file
   ifstream infile;                           //make stream
   infile.open("PERSFILE.DAT", ios::binary);  //open it
   infile.seekg( pn*sizeof(person) );         //move file ptr
   infile.read( (char*)this, sizeof(*this) ); //read one person
   }
//--------------------------------------------------------------
void person::diskOut()           //write person to end of file
   {
   ofstream outfile;             //make stream
                                 //open it
   outfile.open("PERSFILE.DAT", ios::app | ios::binary);
   outfile.write( (char*)this, sizeof(*this) ); //write to it
   }
//--------------------------------------------------------------
int person::diskCount()          //return number of persons
   {                             //in file
   ifstream infile;
   infile.open("PERSFILE.DAT", ios::binary);
   infile.seekg(0, ios::end);    //go to 0 bytes from end
                                 //calculate number of persons
   return (int)infile.tellg() / sizeof(person);
   }
////////////////////////////////////////////////////////////////
int main()
   {
   person p;                     //make an empty person
   char ch;
      
   do {                          //save persons to disk
      cout << "Enter data for person:";
      p.getData();               //get data
      p.diskOut();               //write to disk
      cout << "Do another (y/n)? ";
      cin >> ch;
      }  while(ch=='y');         //until user enters 'n'
   
   int n = person::diskCount();  //how many persons in file?
   cout << "There are " << n << " persons in file\n";
   for(int j=0; j<n; j++)        //for each one,
      {
      cout << "\nPerson " << j; 
      p.diskIn(j);               //read person from disk
      p.showData();              //display person
      }
   cout << endl;
   return 0;
   }
А это код, который не работает.


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <fstream>               //for file streams
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class person                     //class of persons
   {
   protected:
      char name[40];             //person's name
      int age;                   //person's age
   public:
      void getData(void)         //get person's data
         {
         cout << "\n   Enter last name: "; cin >> name;
         cout << "   Enter age: "; cin >> age;
         }
      void showData(void)        //display person's data
         {
         cout << "\n   Name: " << name;
         cout << "\n   Age: " << age;
         }
      void diskIn(int);          //read from file
      void diskOut();            //write to file
      static int diskCount();    //return number of
                                 //   persons in file
   };
//--------------------------------------------------------------
void person::diskIn(int pn)      //read person number pn
   {                             //from file
   fstream infile;                           //make stream
   infile.open("PERSFILE.DAT", ios::binary);  //open it
   infile.seekg( pn*sizeof(person) );         //move file ptr
   infile.read( (char*)this, sizeof(*this) ); //read one person
   }
//--------------------------------------------------------------
void person::diskOut()           //write person to end of file
   {
  fstream outfile;             //make stream
                                 //open it
   outfile.open("PERSFILE.DAT", ios::app | ios::binary);
   outfile.write( (char*)this, sizeof(*this) ); //write to it
   }
//--------------------------------------------------------------
int person::diskCount()          //return number of persons
   {                             //in file
  fstream infile;
   infile.open("PERSFILE.DAT", ios::binary);
   infile.seekg(0, ios::end);    //go to 0 bytes from end
                                 //calculate number of persons
   return (int)infile.tellg() / sizeof(person);
   }
////////////////////////////////////////////////////////////////
int main()
   {
   person p;                     //make an empty person
   char ch;
      
   do {                          //save persons to disk
      cout << "Enter data for person:";
      p.getData();               //get data
      p.diskOut();               //write to disk
      cout << "Do another (y/n)? ";
      cin >> ch;
      }  while(ch=='y');         //until user enters 'n'
   
   int n = person::diskCount();  //how many persons in file?
   cout << "There are " << n << " persons in file\n";
   for(int j=0; j<n; j++)        //for each one,
      {
      cout << "\nPerson " << j; 
      p.diskIn(j);               //read person from disk
      p.showData();              //display person
      }
   cout << endl;
   return 0;
   }
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
26.10.2018, 23:20
Ответы с готовыми решениями:

Почему при начальной загрузке страницы не работает код?
Хочу что бы при загрузке страницы jQuery понимал какая сейчас ширина и сразу же работал скрип при...

Fstream: при запуске программы в IDE, файл не создаётся; почему так происходит?
Доброго времени суток!) Может немного глупый вопрос, но самому решить не получается. Когда собираю...

Почему программа выдает ошибку при первом запуске, а дальше работает нормально? Код C
Подскажите почему программа выдает ошибку при первом запуске, а дальше работает нормально?...

При работе с файлами и потоком fstream builder не хочет компилировать код
При работе с файлами (код содержит запись и считывание с файла ofstream\ifstream) builder выдает...

1
7791 / 6558 / 2984
Регистрация: 14.04.2014
Сообщений: 28,667
26.10.2018, 23:46 2
Ну и зачем это надо?
Флаги in/out добавь.
0
26.10.2018, 23:46
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
26.10.2018, 23:46
Помогаю со студенческими работами здесь

Почему радио перезагружается при переходе между страницами
Здравствуйте уважаемые форумчане. Сделал подгрузку радио на страницу, при перемещении между...

Почему при переходе на TAB Label не получает фокус
Несколько вопросов как с помощью клавиши ТАВ переключиться на оюъъект Label(TAB index я...

Вылетает примерно через 30 минут (при переходе в нет, в стим, или вообще простотак но при переходе)
Здравствуйте у меня windows вылетает на синий экран, внизу появляется отсчет до 100 потом он сам...

При работе fstream указатель типа pos_type (позиции в файле) не работает
Разбираю код с сайта: http://valera.asf.ru/cpp/book/c20.html Компилятор Билдер-6 ругается. когда...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru