fstream 测试程序由于某种原因崩溃
fstream test program crashes for some reason
我一直在使用 C++ 中的 fstream class 来查看我是否能够将一些数据写入文本文件 (.txt)。据我所知,如果程序试图写入一个不存在的文件,那么它会自动创建该文件,我错了吗?这个程序非常简单,没有给我任何编译器错误,这意味着它构建良好。但是由于某种原因,当我 运行 它时它崩溃了。
这是我的代码:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
std::fstream* myFile;
int main()
{
int age = 15;
std::string myName = "Javier Martinez";
std::string friendsName = "David Lyn";
//Backslash is a special character, use double backslash or forward slash instead.
myFile->open("C:/Users/NIKE/Desktop/data.txt");
if (myFile->fail())
{
std::cerr << "File was unable to be opened.";
}
*myFile << age << "\n";
*myFile << myName << "\n";
*myFile << friendsName << "\n";
myFile->close();
std::cout << "File was successfully written to with the data";
return 0;
}
感谢任何帮助。先感谢您。
注意:我使用 GNU GCC 编译器 Code::Blocks IDE
我的文件未初始化。检查它。(分配内存)或简单地使用 fstream。
您的问题源于以下行:
std::fstream* myFile;
您只声明了一个指向流对象的指针,由于它在全局范围内,它被初始化为 nullptr
。事实上,您尝试通过它访问一个不存在的对象(无效),您调用了所谓的 Undefined Behavior.
您不需要在堆上分配流对象,而是:
std::fstream myFile;
旁注:检查你的程序控制流程:
if (!myFile)
{
std::cerr << "File was unable to be opened.";
}
else{
myFile << age << "\n";
myFile << myName << "\n";
myFile << friendsName << "\n";
}
我一直在使用 C++ 中的 fstream class 来查看我是否能够将一些数据写入文本文件 (.txt)。据我所知,如果程序试图写入一个不存在的文件,那么它会自动创建该文件,我错了吗?这个程序非常简单,没有给我任何编译器错误,这意味着它构建良好。但是由于某种原因,当我 运行 它时它崩溃了。
这是我的代码:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
std::fstream* myFile;
int main()
{
int age = 15;
std::string myName = "Javier Martinez";
std::string friendsName = "David Lyn";
//Backslash is a special character, use double backslash or forward slash instead.
myFile->open("C:/Users/NIKE/Desktop/data.txt");
if (myFile->fail())
{
std::cerr << "File was unable to be opened.";
}
*myFile << age << "\n";
*myFile << myName << "\n";
*myFile << friendsName << "\n";
myFile->close();
std::cout << "File was successfully written to with the data";
return 0;
}
感谢任何帮助。先感谢您。 注意:我使用 GNU GCC 编译器 Code::Blocks IDE
我的文件未初始化。检查它。(分配内存)或简单地使用 fstream。
您的问题源于以下行:
std::fstream* myFile;
您只声明了一个指向流对象的指针,由于它在全局范围内,它被初始化为 nullptr
。事实上,您尝试通过它访问一个不存在的对象(无效),您调用了所谓的 Undefined Behavior.
您不需要在堆上分配流对象,而是:
std::fstream myFile;
旁注:检查你的程序控制流程:
if (!myFile)
{
std::cerr << "File was unable to be opened.";
}
else{
myFile << age << "\n";
myFile << myName << "\n";
myFile << friendsName << "\n";
}