Я пытался написать программу, которая использует fstream для чтения и записи целых чисел из текстового файла, но после того, как программа выполнена и вышла из нее, файл не изменяется на все, и содержимое остается неизменным.fstream не перезаписывает содержимое моего текстового файла
Вот краткое описание того, что мой файл должен делать:
- Это приложение читает файл, изменяет его содержание, и записывает изменения обратно в тот же файл.
- Файл содержит 3 строки целых чисел. Первая строка указывает количество целых чисел на третьей строке. Вторая строка указывает, какое целое на третьей строке было выбрано (активно).
- В третьей строке в файле перечислены все целые числа (не более 10).
- Меню, которое постоянно отображается на экране. Прямо под меню программа отображает все целые числа в третьей строке файла
- Программа также отображает, какое целое число выбрано в настоящий момент (активное).
- Пользователь может выбрать элемент меню, нажав одну из расширенных клавиш из меню.
- Нажатие «Вставка» вставляет целое число перед выбранным целым и активирует вновь вставленное целое число. Целое число вводится пользователем. Если список заполнен, вставка будет невозможна.
- Нажатие «Удалить» удаляет активное целое число.
- Нажатие кнопки «Сортировать» сортирует список по возрастанию. Активное целое число после сортировки совпадает с активным целым числом до сортировки.
- Нажатие кнопки «Выбрать» выбирает следующее целое число в списке. Если выбрано последнее целое число, этот параметр выбирает первый элемент в списке.
- Нажатие кнопки «Переместить вправо» перемещает выбранное целое число в одну позицию вправо. Если выбрано последнее целое число, перемещение вправо будет невозможно.
- Нажатие кнопки «Переместить влево» перемещает выбранное целое число на одну позицию влево. Если выбрано первое целое число, перемещение влево будет невозможно.
- Нажатие кнопки «Выход» завершает работу приложения.
- Программа сохраняет содержимое файла в массив, изменяет массив и записывает содержимое массива в файл.
[Моя программа:]
//Description: Grade averages
#include<iostream>
#include<cstdlib>
#include<fstream>//allows file streams
#include<conio.h>
#include<dos.h>
#include <iomanip>
#include <string>
#include <windows.h>
using namespace std;
void menu();//declaration of the menu funtion
int main()
{
int num = 0;
int next = 0;
fstream f_stream;//declares the stream that allows the program to read/write from the file
f_stream.open("base.txt");//opens the file
if (f_stream.fail())//checks if the file is present
{
cout << "base.txt is missing. program cannot run :(" << endl;//displays an error if the file can't be found
exit(1);
}
cout << "input stream successfully opened" << endl;//confirms that the file is available
int ch =0;
int values[12];//declares the array that will store the file's integers
do
{
menu();//displays a menu for inputs
while (!f_stream.eof())//runs until the end of the file is reached
{
f_stream >> next;//grabs values from the file
values[num] = next;//assigns a file input to an expression in the array
num++;//this keeps tally of the number of items in the file
}
cout << endl;
cout << "Here is the list of numbers on the third line: " << endl << endl;
for (int t = 2; t < num; t++)//this displays the values on the third line
{
cout << values[t] << endl;
}
cout << endl;
int num_of_integers = num - 2;//this is the number of files in the 3rd line. the first and second line numbers are subtracted
int active = values[1];//the integer from the second line displays the number that is active
int activenumber = values[active];//grabs the active number
cout << "Number of integers: " << values[0] << endl;
cout << "Current active integer: " << activenumber << endl;
ch=getch();//grabs keyboard input
if (ch == 0||ch == 224)//
ch=getch();//only allows special keys to be used
int newactivenumber;
int lastorder = num - 1;//this is the last element in the array
if (ch == 82)//if the "insert" key is pressed
{
if (num == 12)//if the maximum number of integers is present in the file
{
cout << "Cannot insert an integer before " << activenumber << endl << "Please delete an integer before inserting" << endl;
}
else if (values[active] == values[3])//if the active integer is the very first number on the second line
{
cout << "Please enter an integer to insert at the end of the number line" << endl;
cin >> values[num-1];
}
else//inserts a number before the active integer
{
cout << "Please enter an integer to insert before " << activenumber << endl;
int previous = active - 1;
cin >> values[previous];
}
}
else if (ch == 83)//if the "delete" key is pressed
{
cout << values[active] << " was deleted." << endl;
int temp, temp1;
for (int p = active; p<(lastorder);p++)//shifts all values in the array to the left
{
temp1 = p + 1;
values[p] = values[temp1];
}
int new_integers = num_of_integers - 1;
values[0] = new_integers;//since a value was deleted, the new amount of integers is recorded
num--;
}
else if (ch == 80)//if the "arrow down" key is pressed
{
if (values[1] == lastorder)//if the last number on the list is the active number, then the first number on the list will become the new active number
{
newactivenumber = 2;
values[1] = newactivenumber;
}
else//the next number of the list will become the new active number
{
newactivenumber = values[1] + 1;
values[1] = newactivenumber;
}
cout << values[newactivenumber] << " is now selected" << endl;
}
else if (ch == 77)//if "arrow right" is pressed, the active number is shifter to the right
{
if (values[active] == values[num-1])//disallows shifting if the active number is the last number on the list
{
cout << "I'm sorry, Dave. I'm afraid I can't do that." << endl;
}
else
{
int temp;
temp = values[active];
int rightno = active + 1;
values[active] = values[rightno];
values[rightno] = temp;
cout << "The active number has been moved 1 position right in the list" << endl;
}
}
else if (ch == 60)//IF the F2 key is pressed, the array numbers are sorted from smallest to greatest
{
int i;
int temporary = values[active];
for(i=2;i<num;i++)
{
for(int j=2;j<num-i-1;j++)
{
if(values[j]>values[j+1])
{
int temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
//displaying result
cout<<"Sorted list"<<endl;
for(i=2;i<num;i++)
{
cout<<values[i] << endl;
}
for(i=2;i<num;i++)//this loop ensures that the active number remain the same, even after the sorting
{
if (values[i] == activenumber)
{
values[1] = i;
}
}
}
else if (ch == 75)//if "arrow left" is pressed, it shifts active number to the left
{
if (values[active] == values[2])//
{
cout << "I'm sorry, Dave. I,'m afraid I can't do that." << endl;
}
else
{
int temp;
temp = values[active];
int leftno = active - 1;
values[active] = values[leftno];
values[leftno] = temp;
cout << "The active number has been moved 1 position left in the list" << endl;
}
}
else if (ch == 59)//terminates program if F1 is pressed
{
f_stream.close();
cout << "streams successfully closed" << endl;
break;
}
else//if an invalid key is pressed
{
cout << "Try again" << endl;
}
for (int out = 0; out < num; out++)//exports array values to the file
{
if (out == 0 || out == 1)
{
f_stream << values[out] << '\n';
}
else if (values[out]==0)
{
f_stream << "";
}
else if (out != num-1)
{
f_stream << values[out] << " ";
}
else
{
f_stream << values[out];
}
}
system("PAUSE");
system("CLS");
}
while (ch != 59);
f_stream.close();
cout << "streams successfully closed" << endl;
return 0;
}
void menu()//self-explanatory
{
cout<<"Menu:" << endl;
cout << setiosflags(ios::left) << setw(14)<< "1.Insert" << "Press the \"Insert\" key" << endl;
cout << setiosflags(ios::left) << setw(14)<< "2.Delete" << "Press the \"Delete\" key" << endl;
cout << setiosflags(ios::left) << setw(14)<< "3.Sort" << "Press the \"F2\" key:" << endl;
cout << setiosflags(ios::left) << setw(14)<< "4.Select" << "Press the \"Down Arrow\" key" << endl;
cout << setiosflags(ios::left) << setw(14)<< "5.Move Right" << "Press the \"Right Arrow\" key" << endl;
cout << setiosflags(ios::left) << setw(14)<< "6.Move Left" << "Press the \"Left Arrow\" key" << endl;
cout << setiosflags(ios::left) << setw(14)<< "7.Exit"<< "Press the \"F1\" key" << endl;
}
[Base.txt]
10
9
-23 5 23 56 0 -32 3 9 11 66
«Вот краткое описание того, что мой файл должен делать:» ... на самом деле? – quantdev
Вы можете открыть fstream для ввода или вывода, а не для обоих. – stark