【问题标题】:c++ write to a file, but file is emptyc ++写入文件,但文件为空
【发布时间】:2014-04-12 22:01:53
【问题描述】:

我有将十进制转换为二进制并将其写入文件的代码:

#include <iostream>
#include <fstream>

using namespace std;

int d,num,s,r,k,sum=0;;

void main()
    {
        ofstream myfile;
        myfile.open("binary.txt",ios::in);
        cin >> d;
        while(d>0)
        {
            r=d%2;
            sum=sum + (k*r);
            d=d/2;
            k=k*10;     
            myfile << sum;
        }  
        cout << "Encryption Succesfull"<<endl;
        myfile.close();
    }

程序运行成功,但文件为空。

文件名正确,没有语法错误等

怎么办?

【问题讨论】:

  • 你是否进入了while 循环?
  • 用适度优化编译(即,对于 GCC,至少 -O)和至少 all 默认警告(即,-Wall)。它应该告诉你你正在使用变量而不给它们赋值(至少k在我对代码的表面扫描中)。

标签: c++ file io decimal converter


【解决方案1】:

您打开文件时使用了错误的标志:

myfile.open("binary.txt",ios::in);

应该是

myfile.open("binary.txt",ios::out | ios::binary);

【讨论】:

    【解决方案2】:
    myfile.open("binary.txt",ios::in);
    

    打开文件进行阅读。如果您想输出某些内容,请使用ios::out 或将参数留空(因为无论如何默认值为ios_base::out):

    myFile.open("binary.txt");
    

    我在 cplusplus.com 上找到了这条线,但它似乎不是真的(在 devC++ 4.9.9.2 上测试,使用了一些 MinGW 版本):

    out 总是为 ofstream 对象设置(即使在参数模式下明确没有设置)。

    删除第二个参数或将其更改为ios::out 确实可以解决问题。

    【讨论】:

    • 并且可以通过构造函数打开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多