I'm working on a function within a larger program that asks the user to input the name of a file. If the file exists, the program is supposed to print out the text contained within the file. If the file doesn't exist, it's supposed to tell the user and then exit.
This function works perfectly if I build it as its own program. However, if I add the code to the larger program as a function, when the program runs it runs very quickly, doesn't allow the user an opportunity to input a file name and then promptly exits.
Any help would be appreciated. My initial thought is that this is related to information being passed to, or from, the main program.
cout<<"***************************************\n";
cout<<"***************************************\n";
cout<<"Type 1 to enter and save a record \n";
cout<<"Type 2 to search for a record \n";
cout<<"Type 3 to delete a record \n";
cout<<"Type 4 to exit this program \n";
cout<<"***************************************\n";
cout<<"***************************************\n";
cout<<"\n";
do
{
cout<<"Please enter your selection: ";
cin>>selection;
switch (selection) {
case 1:
cout<<"You have chosen to enter and save a record\n";
save();
system("pause");
break;
case 2:
cout<<"You have chosen to read from a record\n";
read();
system("pause");
break;
case 3:
cout<<"You have chosen to delete a record\n";
del();
system("pause");
break;
case 4:
cout<<"You have chosen to exit this program\n";
bExit = true;
break;
}
} while (!bExit);
return 0;
}
int read()
{
using namespace std;
char filename[50];
cout<<"Please enter a filename: ";
cin.getline(filename,50);
ifstream bucky;
bucky.open(filename);
if (!bucky.is_open()) {
cout<<"That file is not available\n";
exit(EXIT_FAILURE);
}
char word[50];
bucky >> word;
while (bucky.good()) {
cout << word << " ";
bucky>> word;
}
getline reads a line. A line is something that ends with \n.
istream::operator >>, on the other hand, is not so specific about what it reads. Firstly it skips any ' ', '\t' and '\n', then reads a bunch of characters and stops at first ' ', etc. or any non-digit if your >> is reading a number (that last part isn't exactly true for '.', '+', '-' and 'e' ..).