Hi this is a very simple piece of code I just write for C++ file i/o practice. But I got a Segmentation Fault (core dumped) exception when I am running this.
Here is my code below:
# include <iostream>
# include <string>
# include <cmath>
# include <fstream>
using namespace std;
int main()
{
double num, rad, i, angle, x, y;
char * filename;
ofstream file;
// prompt ask for number
cout << "Enter the number of sample points: ";
cin >> num;
// prompt for circle radius.
cout << "Enter the circle radius: ";
cin >> rad;
// prompt for output file name.
cout << "Enter the output filename: ";
cin >> filename;
file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
cout << "Error opening file " << filename << endl;
cout << "Exiting..." << endl;
return 0;
}
for(i = 1; i <= num; i ++)
{
//angle = 2 * M_PI * (i/num);
//x = rad * cos(angle);
//y = rad * sin(angle);
//file << "\t" << x << "\t" << y << endl;
file << "this is " << i << endl;
}
cout << "finished";
file.close();
return 0;
}
I am not sure where the problem is, but the error message “seg fault (core dumped)”shows up after Enter the output file name.
Thank you
cin >> filenamewill be undefined behaviour, becausefilenameis an uninitialized pointer.If you want to store characters, you need to allocate space for them. So you could do:
or: