-2

我的程序在用户输入 outputFileName 后崩溃。 c1是一个 char 数组,out是一个字符串,len是一个长度为 c1 的 int。

这是我的代码:

    ofstream outFile;
    char outputFileName[256];
    cout << "Enter output file name: ";
    cin >> outputFileName;
    cout << endl;
    outFile.open(outputFileName,ios::trunc);
    for(int i=0; i<len-1; i++){ //-1 b/c added \n at the end.
        out[i] = c1[i];
    }
    outFile << out;
    outFile.close();
4

2 回答 2

2

我想我会做更多这样的事情:

{    
    std::cout << "Please enter output file name: ";

    std::string outputFileName;       
    std::getline(outputFileName, std::cin);

    std::ofstream outputFile(outputFileName.c_str());
    outputFile.write((static_cast<char *>(&c1), len);
} // file closes automatically when it goes out of scope.
于 2013-07-07T08:30:11.070 回答
0

我修复了它摆脱并将 c1 直接写入文件。

ofstream outFile;
char outputFileName[256];
cout << "Enter output file name: ";
cin >> outputFileName;
cout << endl; outFile.open(outputFileName,ios::trunc);
for(int i=0; i<len-1; i++){ //-1 b/c added \n at the end. 
    outFile = c1[i];
} 
outFile.close();
于 2013-07-07T22:27:00.780 回答