Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将错误内容写入文件的流_C++ - Fatal编程技术网

C++ 将错误内容写入文件的流

C++ 将错误内容写入文件的流,c++,C++,嘿,伙计们,我真的想不出标题中的这个错误应该怎么称呼,所以现在开始 我正在开始一项作业,我必须读取文件的内容,执行一些计算,然后将内容+新计算写入文件 我编写代码读取文件,并立即将其写入输出文件,以测试读取是否正确。当我这样做的时候,我看到一个流在随机的地方将我的“filename”字符串(用于要求用户输入要打开的文件名)写入文件,而代码中没有提到它 这是我的密码: #include <string> #include <fstream> #incl

嘿,伙计们,我真的想不出标题中的这个错误应该怎么称呼,所以现在开始

我正在开始一项作业,我必须读取文件的内容,执行一些计算,然后将内容+新计算写入文件

我编写代码读取文件,并立即将其写入输出文件,以测试读取是否正确。当我这样做的时候,我看到一个流在随机的地方将我的“filename”字符串(用于要求用户输入要打开的文件名)写入文件,而代码中没有提到它

这是我的密码:

   #include <string>
    #include <fstream>
    #include <vector>
    #include <iostream>
    using namespace std;

    int main()  
    {
     char filename[256] = "";
     char currentLine[256] = ""; 

     cout << "Please enter the name of the input file: " << endl;
     cin.getline(filename,256);

     vector <string> storage;//disregard for now

     ifstream infile;
     infile.open(filename);

     string outputFile = ".output";
     outputFile = filename + outputFile;

     ofstream outfile(outputFile.c_str());

     string line = "";
     while(!infile.eof())
     {
      infile.read(currentLine, 256);
      line = currentLine;
      storage.push_back(line); //disregard for now
      outfile << line; //testing to see if it read properly
     }
    } 
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符文件名[256]=“”;
字符currentLine[256]=“”;

cout逐行读取文件的正确方法是:

string line;
while( getline( file, line ) ) {
   // do something with line
}

关于为什么会这样,你可能想看看我的问题。

我想你的问题在这里:

infile.read(currentLine, 256);
因为我注意到

是一个未格式化的输入函数,提取的内容不会存储为c字符串格式,因此不会在字符序列的末尾追加结尾空字符


因此,当您转到复制currentLine时,副本会从末尾进入内存中的任何其他内容,即
filename

,您确定启动.output文件时是空的吗?顺便说一句--我已经看到了一些与家庭作业相关的更清晰的问题,您值得推荐。没关系-它将被覆盖。但他应该检查它是否正确打开。谢谢^-^,是的,每次都会重写输出文件。它似乎也正确打开,您的确切意思是什么?他的意思是您没有处理流输出文件(outputFile.c_str())的
失败了。非常感谢,我现在就去读它,让你知道它是如何产生的。谢谢!这修复了它,我学到了一个最佳实践,所以非常感谢!!