While playing around a bit with File I/O I created a small test program. It displays a menu, from which the use can select two functions. One to write a string to a specified file and one to read a file. Now it all works if I call the functions within main. However if I call the functions from the menu function the do not function like they should, like skipping any user input. What exactly is going wrong? There are not compile errors btw. I suspect some variable scope issue but I can not find the error.
Code:
// File IO Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
void printfile();
void readfile();
void menu();
int main() {
menu();
return 0;
}
void menu() {
int x;
cout<<"<1> Print file function"<<endl;
cout<<"<2> Read file function"<<endl;
cout<<"<0> Exit program"<<endl;
cout<<"Select funtion and press <ENTER>): ";
cin>>x;
if (x < 0 || x > 2) {
cout<<"<ERROR> Invalid menu selection. Exiting program..."<<endl;
}
else {
switch (x)
{
case 1:
printfile();
break;
case 2:
readfile();
break;
case 0:
cout<<"<0> Exiting...."<<endl;
break;
}
}
}
void readfile() {
char filename[81];
char content[81];
cout<<"Enter a filename and press ENTER: ";
cin.getline(filename, 80);
ifstream file_in(filename);
file_in.getline(content, 80);
cout<<content<<endl;
}
void printfile () {
char filename[81];
char content[81];
cout<<"Enter the filename: ";
cin.getline(filename, 80);
ofstream file_out (filename);
cout<<"Enter text to write to file: ";
cin.getline(content, 80);
file_out<<content<<endl;
file_out.close();
}
So again in short: If I call the printfile or readfile function directly in main it works, but going from main > menu() > readfile() it starts acting weird.