c++ - 即使关闭流,也会出现混合 fstream 流问题

标签 c++

我在使用以下代码时遇到问题。

如果我杀死读取部分,它可以写得很好。 如果我杀死写入部分并且文件已经写入,它可以正常读取。 2人互不喜欢。就像写流没有关闭......虽然它应该是。

怎么了?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
 string a[5];
 a[0]= "this is a sentence.";
 a[1]= "that";
 a[2]= "here";
 a[3]= "there";
 a[4]= "why";
 a[5]= "who";

 //Write some stuff to a file
 ofstream outFile("data.txt");     //create out stream
 if (outFile.is_open()){       //ensure stream exists
  for (int i=0; i< 5; i++){
   if(! (outFile << a[i] << endl)){    //write row of stuff
    cout << "Error durring writting line" << endl; //ensure write was successfull
    exit(1);
   }
  }
  outFile.close();
 }

 //Read the stuff back from the file
 if(!outFile.is_open()){  //Only READ if WRITE STREAM was closed.
  string sTemp;   //temporary string buffer
  int j=0;    //count number of lines in txt file

  ifstream inFile("data.txt");  
  if (inFile.is_open()){
   while (!inFile.eof()){
    if(! (getline(inFile, sTemp)) ){    //read line into garbage variable, and ensure read of line was
     if(!inFile.eof()){       //successfull accounting for eof fail condition.
      cout << "Error durring reading line" << endl; 
      exit(1);
     }
    }
    cout << sTemp << endl;  //display line on monitor.
    j++;      
   }
   inFile.close();
  }
  cout << (j -1) << endl;  //Print number lines, minus eof line.
 }

 return 0;
}

最佳答案

你有一个内存覆盖。

你有六个字符串,但只有五个字符串的维度

 string a[5];
 a[0]= "this is a sentence.";
 a[1]= "that";
 a[2]= "here";
 a[3]= "there";
 a[4]= "why";
 a[5]= "who";

这可能会导致程序的其余部分出现意外行为。

关于c++ - 即使关闭流,也会出现混合 fstream 流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648604/

相关文章:

c++ - "Nested"scoped_lock

c++ - 为什么这个 type_traits 代码给我一个整数到指针转换警告?

c++ - 反转具有循环的链表

c++ - 将继承与静态函数一起使用

c++ - 使用英特尔 C++ 编译器在 C++ 中实现 MATLAB 函数

C++ 向量化 vector 的 vector

java - 类路径问题 - getJNIEnv 失败

c++ - 在C++中使用指向内部类对象的指针作为外部类构造函数参数

c++ - 非实例化 C++ 模板函数的语义正确性

c++ - 二次方程 : negative discriminant in C++