您好,这是我为 C++ 文件 i/o 练习编写的一段非常简单的代码。但是当我运行它时,我得到了一个 Segmentation Fault (core dumped)
异常。
下面是我的代码:
# 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;
}
我不确定问题出在哪里,但在输入输出文件名后出现错误消息“seg fault (core dumped)”。
谢谢
最佳答案
cin >> filename
将是未定义的行为,因为 filename
是一个未初始化的指针。
如果要存储字符,需要为其分配空间。所以你可以这样做:
char filename[150] = {0};
cin >> filename; // OK, you provide space for 149 characters. Will still break
// if more characters are provided by the user.
或:
#include <string>
std::string filename; // overloads operators >> and << with streams
// automatically performs memory management
// std::cin >> filename; /* Would stop at first space */
std::getline(std::cin, filename); // better: will stop at any carriage return
关于c++ - 写入文件时核心转储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9124320/