ZFGC
Resources => Coding => Topic started by: PoeFacedKilla on March 20, 2011, 08:01:54 pm
-
Ok, so i've written a small program to test my knowledge of file i/o. The source code compiles, and creates an excutable. But when I run the program, after I input the first variable a window pops up (im using vista) and says the program stopped running. Can anyone compile this and see if they get the same error, or can you tell me how to fix it?
#include <iostream>
#include <fstream>
using namespace std;
char* write_to_file( char* file_src, char* file_txt )
{
ofstream myFile;
myFile.open( file_src );
myFile << file_txt;
myFile.close();
}
int main()
{
char* input_src; char* input_txt;
cout << "Please Enter The File Name: ";
cin >> input_src;
cin.get();
system("CLS");
cout << "Enter Text to be Displayed in File: ";
cin >> input_txt;
cin.get();
system("CLS");
write_to_file( input_src, input_txt );
cout << input_txt; cout << " - Written to File";
cin.get();
return 0;
}
any help is greatly appreciated.
-
Well first thing you should do in scenarios like this is run the program in Debug mode and find at what line the program crashes
Tell us what line it gets stuck on
-
Try this
#include <iostream>
#include <fstream>
using namespace std;
void write_to_file( char* file_src, char* file_txt )
{
ofstream myFile;
myFile.open( file_src );
myFile << file_txt;
myFile.close();
}
int main()
{
char* input_src; char* input_txt;
cout << "Please Enter The File Name: ";
cin >> input_src;
cin.get();
system("CLS");
cout << "Enter Text to be Displayed in File: ";
cin >> input_txt;
cin.get();
system("CLS");
write_to_file( input_src, input_txt );
cout << input_txt; cout << " - Written to File";
cin.get();
return 0;
}
-
I'm gonna go out on a whim and say it's because your using cin on a pointer, so it's expecting a memory address. Try this for cin:
cin >> *input_src;
If that still doesn't work for you, then my suggestion is to move away from char pointers and just use an std::string instead. If you need the data in char form, you can use std::string.c_str().