Fel*_*bek 3 c++ file-io compiler-errors
我不明白为什么我的编译器 (MSVC++2010) 不喜欢这个代码:
// 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());
}
Run Code Online (Sandbox Code Playgroud)
我收到这些错误(我将它们从德语翻译成英语,并为代码摘录提供了正确的行号,而没有前导注释):
错误 1 错误 C2079:'bill_buf' 使用未定义的类 'std::basic_stringbuf<_Elem,_Traits,_Alloc>'(第 2 行)
错误 2 错误 C2664:“std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std::streamsize)”:将参数 1 从“int”转换为“char *” ' 不可能(第 5 行)
错误 3 错误 C2228:“.str”的左侧必须有一个类/结构/联合。(第 7 行)
有没有人知道那里发生了什么?非常感谢!(如果有人更好地了解如何快速将整个文件内容转换为字符串,我也将不胜感激)
你缺少一个包含。这是您的代码,这次不使用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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5080 次 |
| 最近记录: |