I recently learned how to read and write text files within a C++ program(well, I feel I may have missed something in the lesson because I see no reason why this shouldn't work.) However, upon executing the program, the file is never created and the program instantly closes. Below is a rendition of what I am trying to do. The program is designed to write user input to the text file.
#include <iostream>
#include "File1.h"
usingnamespace std;
void classD(); //function to input program selection
void runClass(); //function to call the first function in the class
void runClass2(); //function to call the second function in the class
int main(){
classD();
return 0;}
void classD(){
int a; //program decision variable
cout<<"Enter a number corresponding to the program you wish to run."<<endl<<"1) Hello World Variation\n2) ''Notepad'' in the Command Prompt"<<endl<<endl;
cin>>a;
switch(a){ //check for input value
case 1:
runClass(); //see forward declaration/prototype of function call
break;
case 2:
runClass2(); //see forward declaration/prototype of function call
break;
default:
cout<<"invalid number"<<endl;
return;}//input that isn't a number or is not equal to a corresponding number's program will be counted as invalid input
}
void runClass(){
File1 file1;
file1.functionA();}
void runClass2(){
File1 file2;
file2.functionC();}
header file for class used(File1.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef FILE1_H
#define FILE1_H
#include <iostream>
usingnamespace std;
class File1{
public:
File1();//constructor currently does nothing
void functionA(); //first program in the list, a variation of "Hello World"
void functionB(); //unwritten function to be written later
void functionC(); //second program in the list, attempt to create a text editor in command prompt
private:
};
#endif // FILE1_H
source file for class(File1.cpp):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "File1.h"
#include <conio.h>
#include <fstream>
File1::File1(){ }
void File1::functionA(){
cout<<"This is a sentence."<<endl;}
void File1::functionB(){}
void File1::functionC(){
string in; //variable reprisenting input
in = getch(); //input equal to input via keystrokes
ofstream inputO;
inputO.open("Text File.txt"); //creation of text file to be written
inputO<<in;}//file contents are set equal to input
Thanks for all the help, I really appreciate it. Furtonately, I figured out that the file was being saved to a difference folder than where the source folder was. I'm also glad you reminded me about the .close() because I'm pretty sure I would've run into more problems down the road without that.