C++没有在Codeblocks中命名类型错误

Del*_*D0D -7 c++ codeblocks ifstream

我正在尝试在代码块中编译这个简单的C++程序:

#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>

std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
std::stringstream buffer;
buffer << t.rdbuf();
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

|| === Build:在hostapp2中调试(编译器:GNU GCC编译器)=== |

C:\ Users\Flights Trainer\Desktop\hostapp2\main.cpp | 7 |错误:'缓冲'不命名类型

|| ===构建失败:1个错误,0个警告(0分钟,0秒(s))=== |

我一整天都在谷歌搜索"没有命名类型",我发现的所有内容都指向在宣布之前使用类,但我不明白我在做什么.

我究竟做错了什么?

Tar*_*ama 5

你不能在C++文件范围内放置任意语句,你需要将它们放在一个函数中.

#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>

int main () {
    //These are now local variables
    std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
    std::stringstream buffer;

    //We can write expression statements because we're in a function
    buffer << t.rdbuf();
}
Run Code Online (Sandbox Code Playgroud)