gpt4 book ai didi

c++ - 尝试将 char[] 写入文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:48 25 4
gpt4 key购买 nike

我试图将 char[256] 写入文本文件。以下是我目前的工作:

         fstream ofs;
ofs.open("c:\\myURL.txt");
ofs.write((char*)testDest,256);
ofs.close();

还是不行。

这里是错误:

错误 C2440:“类型转换”:无法从“”转换为“char *”

更新:

到目前为止,这是我的进度尝试,代码可以编译,但是运行时,我的程序突然终止。

    ofstream stream;
CBar *a;

switch(uMessage) {
case WM_PAINT:
return bar->OnPaint();
case WM_ERASEBKGND:
return 1;
case WM_LBUTTONDOWN: //wira
if (!bar->OnClick(wParam, lParam)) {
stream.open("C:\\myURL.txt");
stream << a->testDest << endl; // if I replace `a->testDest` with "testword" string, my prgrom does not terminated. Why?
return 0;
}
break;

最佳答案

您的代码中有几处错误或“不好”:

  1. 您永远不会检查打开是否失败。
  2. 您使用笨拙的write 函数。
  3. 您不检查您的写入是否成功(如果您确定它会工作,则不是很有必要)。

如果出现问题,这将为您提供更多信息:

#include <fstream>
using std::ofstream;
#include <iostream>
using std::cout;
using std::endl;

int main()
{
ofstream stream;
char charArray[] = "Some stuff in a char array.";

stream.open("C:\\myurl.txt");
if( !stream )
cout << "Opening file failed" << endl;
// use operator<< for clarity
stream << testDest << endl;
// test if write was succesful - not *really* necessary
if( !stream )
cout << "Write failed" << endl;

return 0;
}

我的猜测是打开文件失败是因为您缺少适当的权限。上面的程序会告诉你哪里失败了。

更新:要回答你的第二个问题:你这样做:

CBar* a;

它创建了一个指针但保留了它的单元化。然后您想要取消引用它以访问其 testDest 数据成员,这显然会导致崩溃。你需要初始化你的指针(或者不要在这里使用指针,我认为没有理由这样做):

// Either this
CBar* a = new CBar(/*some arguments, or none, depending on CBar definition*/);
//...
cout << a->testDest << endl;

// Or this (better here in my opinion)
CBar a; // OK if there is a default constructor (one with no arguments);
//...
cout << a.testDest << endl;

请阅读任何关于 C++ 的优秀教程。这些是您三天未 sleep 或不了解语言的基本概念时所犯的错误。

关于c++ - 尝试将 char[] 写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3811328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com