C++ compiler error with stringbuf / ifstream
I cannot understand why my compiler (MSVC++2010) doesn't like this code:
// get_sum(filename as c-string) returns sum from file
int get_sum(const char* const s) {
stringbuf bill_buf;
ifstream bill_file;
bill_file.open(s);
bill_file.get(bill_buf, '\0'); // read whole file
bill_file.close();
return get_sum_from_string(bill_buf.str());
}
I get these errors (I translated them from German to English and give the correct line numbers for the code excerpt without leading comment):
Error 1 error C2079: 'bill_buf' uses undefined class 'std::basic_stringbuf<_Elem,_Traits,_Alloc>' (Line 2)
Error 2 error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std::streamsize)': Conversion of parameter 1 from 'int' to 'ch开发者_运维知识库ar *' not possible (Line 5)
Error 3 error C2228: To the left of ".str" there must be a class/structure/union. (Line 7)
Has anyone got an idea what's going on there? Thanks a lot! (If anyone has got a better idea how to quickly get the whole file contents into a string, I'd also appreciate it)
You're missing an include. Here's your code, this time without using streambuf
:
#include<fstream>
#include<string>
#include<iterator>
int get_sum(const char* const s) {
std::ifstream bill_file(s);
std::string contents((std::istreambuf_iterator<char>(bill_file)),
std::istreambuf_iterator<char>());
return get_sum_from_string(contents);
}
For #1, you probably forgot to #include <sstream>
and only have a forward declaration from some other header in scope. #2 and #3 are follow-up errors, don't mind them, fix #1 first and go on.
Looks like you need to #include <sstream>
.
1) In your header file (.h) you should specify "using namespace std". Otherwise, all your stream operations/variables etc have to start with 'std::'
2) Have you included the right headers? You should add
#include <sstream>
精彩评论