爲什麼我的程序轟然倒下:計劃與istream_iterator轟然倒下
#ifndef StreamBuffer_h
#define StreamBuffer_h
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
enum StreamBufferState
{
STREAMBUFFER_OK = 0,
STREAMBUFFER_EOF = 1
};
// gzip plik
// type plik | gzip -d
// gzip -d plik.gz
// gzip -dc plik.gz
class StreamBuffer
{
istream_iterator<char> iter;
int maxBufferSize;
std::string buffer;
public:
StreamBuffer(int maxBuffSize, bool streamInput, std::string filename="")
{
SetMaxBufferSize(maxBuffSize);
if(streamInput) // Wejscie strumieniowe
iter = istream_iterator<char>(std::cin);
else // Wejscie plikowe
iter = istream_iterator<char>(fstream(filename.c_str()));
}
~StreamBuffer()
{
}
void SetMaxBufferSize(unsigned int maxBuffSize)
{
maxBufferSize = maxBuffSize;
}
StreamBufferState FullBufferWithData()
{
char c;
istream_iterator<char> iend;
for(int i=0;i<maxBufferSize;++i)
{
if(iter==iend)
return STREAMBUFFER_EOF;
c << *iter;
buffer += c; // !!!!!! In this line program is crashing down
iter++;
}
return STREAMBUFFER_EOF;
}
std::string GetDataBuffer()
{
return buffer;
}
};
#endif
Error: Run-Time Check Failure #3 - The variable 'c' is being used without being initialized.
行錯誤:
buffer += c; // !!!!!! In this line program is crashing down
[編輯] 改善我的代碼後,我有:
#ifndef StreamBuffer_h
#define StreamBuffer_h
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
enum StreamBufferState
{
STREAMBUFFER_OK = 0,
STREAMBUFFER_EOF = 1
};
// gzip plik
// type plik | gzip -d
// gzip -d plik.gz
// gzip -dc plik.gz
class StreamBuffer
{
fstream file;
istream_iterator<char> iter;
int maxBufferSize;
std::string buffer;
public:
StreamBuffer(int maxBuffSize, bool streamInput, std::string filename="")
{
SetMaxBufferSize(maxBuffSize);
if(streamInput) // Wejscie strumieniowe
iter = istream_iterator<char>(std::cin);
else // Wejscie plikowe
{
file.open(filename.c_str(),ios::in);
iter = istream_iterator<char>(file);
}
}
~StreamBuffer()
{
file.close();
}
void SetMaxBufferSize(unsigned int maxBuffSize)
{
maxBufferSize = maxBuffSize;
}
StreamBufferState FullBufferWithData()
{
char c;
istream_iterator<char> iend;
for(int i=0;i<maxBufferSize;++i)
{
if(iter==iend)
return STREAMBUFFER_EOF;
c = *iter;
buffer += c;
iter++;
}
return STREAMBUFFER_EOF;
}
std::string GetDataBuffer()
{
string buf = buffer;
buffer.clear();
return buf;
}
};
#endif
I還有一個問題:當我用流迭代器讀取字符時,會忽略新的行(和空格),爲什麼?
你爲什麼要在char上做二進制移位? – Geoffroy
你應該閱讀[Eric Lippert的這篇博客文章](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/),瞭解如何調試諸如你的小程序。 –
istream_iterator解引用並將其賦值給c變量會產生垃圾,但我不知道爲什麼。 – CppMonster