Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):

  1. Error 1 error C2079: 'bill_buf' uses undefined class 'std::basic_stringbuf<_Elem,_Traits,_Alloc>' (Line 2)

  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 'char *' not possible (Line 5)

  3. 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)

like image 772
Felix Dombek Avatar asked Apr 15 '26 10:04

Felix Dombek


2 Answers

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);
}
like image 130
wilhelmtell Avatar answered Apr 18 '26 01:04

wilhelmtell


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.

like image 35
etarion Avatar answered Apr 18 '26 01:04

etarion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!