function problem with file i/o

Okay here's my problem the program compile but when i select option 1 it gives me the fatal error message, when i select option 2 it just closes and i dont see anything. What is wrong here? I tried both read and write functions as sepparate programs and they work fine? Whats going on? Any help would be appreciated. Thanks


#include <fstream.h>
#include <iostream.h>
#include <stdlib.h>
#include <stack.h>

void write();
void read();
void handle_choice(int choice);

int main ()
{

do
{
float choice, close;
cout << "1 - Read\n";
cout << "2 - Write\n";
cin >> choice;

handle_choice(choice);
} while (choice != 0);
return 0;
}

void handle_choice(int choice)
{
switch(choice)
{case 1:
read();
break;
case 2:
write();
break;
default :
cout << "Critical Error\n";
break;
}
}

void read()
{

float close;
char user_name[25];
char user_age[4];
int age;
cout << "Opening file for reading...\n";
ifstream infile;
infile.open("NAME_AGE.txt",ios::in);

if (infile)
{
infile.get(user_name,25);
infile.ignore(80,'\n');
infile.get(user_age,2);
infile.ignore(80,'\n');
age = atoi(user_age);
cout << "The name read from the file is " << user_name << '\n';
cout << "The age read from the file is " << user_age << '\n';
infile.close();
cin.get();
cin.get();
}
else
{
cout << "Error opening file for reading.\n";
cin.get();
cin.get();
}
}

void write()
{

float close;
char user_name[50];
char age[50];
ofstream outfile;
cout << "Enter data to be written: ";
cin.get(user_name, 50);
cout << "Enter your age: ";
cin.get (age, 50);
cin.get();
cin.get();

outfile.open("NAME_AGE.txt",ios::out);

if (outfile)
{
outfile << user_name << endl;
outfile << age << endl;
cout << "Write successfull.";
outfile.close();
}
else
{
cout << "Error writing file.";
cin >> close;
}
}
user_name doesn't have space for a null if the input is 25 or more characters.
okay well I got option 1 working but when I select option 2, the program just exits??

Actually I was able to figure it out, it turned out I needed to add some cin.ignore statements.
Topic archived. No new replies allowed.