-7

I'm trying to compile this simple C++ program in Code Blocks:

#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();

And I get this error:

||=== Build: Debug in hostapp2 (compiler: GNU GCC Compiler) ===|

C:\Users\Flights Trainer\Desktop\hostapp2\main.cpp|7|error: 'buffer' does not name a type|

||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I've been googling "does not name a type" all night and everything I've found points to using a class before it has been declared but I dont understand where I am doing that.

What am I doing wrong?

Community
  • 1
  • 1
Wesley Smith
  • 17,890
  • 15
  • 70
  • 121

2 Answers2

5

You can't put arbitrary statements at the file scope in C++, you need to put them in a function.

#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();
}
TartanLlama
  • 59,364
  • 11
  • 141
  • 183
  • Thanks that makes sense, I was working off of [this answer](http://stackoverflow.com/a/2602060/1376624) where that didnt seem to be the case but I understand now. First time working with C++ Thank you. – Wesley Smith Nov 25 '15 at 08:13
  • @DelightedD0D if you're newby in C++, than code at linked question is not the code you want to read) – Lapshin Dmitry Nov 25 '15 at 08:19
  • @LapshinDmitry That's a fair statement. I'm a PHP / Javascript developer. I need to make a very simple C++ program that performs that function and one other to work with a Chrome extension I'm making. Honestly, I'm not trying to learn C++, I just need this one small program to work. – Wesley Smith Nov 25 '15 at 08:21
  • 1
    @DelightedD0D then just know: C++ is not script language, all your code that does something goes to funtions (except template magic), and `main()` is called. – Lapshin Dmitry Nov 25 '15 at 08:24
2

If your code is just as you wrote, that you're having fun. Since it's not code in function, you're basicly declaring varibales, classes and functions -- that's all you can do at global scope.

//Global variable with type ifstream, named t
std::ifstream t("C:/Windows/System32/drivers/etc/hosts-backup.txt");
//Global variable with type stringstream, named buffer
std::stringstream buffer;
//Global variable with type buffer... Em what?!
buffer << t.rdbuf();

That's what an error you're getting. In C++, you can write statements to be executed only in functions.

Lapshin Dmitry
  • 951
  • 6
  • 24