我在使用以下代码时遇到问题。
如果我杀死读取部分,它可以写得很好。 如果我杀死写入部分并且文件已经写入,它可以正常读取。 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/