0

I have this simple code:

std::ifstream ifs;
ifs.open ("test.txt", std::ifstream::in);
char c = ifs.get();
while (ifs.good()) {
   std::cout << c;
   c = ifs.get();
}
ifs.close();

But I am getting a lot of error? such as:

Error   9   error C3083: 'ifstream': the symbol to the left of a '::' must be a type    test.cpp    
Error   8   error C2228: left of '.open' must have class/struct/union   test.cpp

and so on.

I have these definitions at the start of file

#include <iostream>
#include <fstream>
#include "stdafx.h"
using namespace std;

I am using VS2012 on a console application.

edit1:

The complete code is as follow:

void ReadRawImages::Read(int frameNumber)
{
std::ifstream ifs;

      ifs.open ("test.txt", std::ifstream::in);

       char c = ifs.get();

       while (ifs.good()) {
            std::cout << c;
            c = ifs.get();
       }

  ifs.close();


 }

I also noted that I have these warnings:

Warning 1   warning C4627: '#include <iostream>': skipped when looking for precompiled header use   test.cpp
Warning 2   warning C4627: '#include <fstream>': skipped when looking for precompiled header use    test.cpp
Matthieu Rouget
  • 3,289
  • 18
  • 23
mans
  • 17,104
  • 45
  • 172
  • 321
  • 1
    Can you post the code immediately before `std::ifstream ifs;`? Possibly you missed a semicolon somewhere earlier. – Roger Rowland May 23 '13 at 11:29
  • ditch the line "using namespace std" as you use std:: comprehensively – Bathsheba May 23 '13 at 11:31
  • [Your code works fine](http://eval.in/31344). Did you wrap that code in a function at all? – Niels Keurentjes May 23 '13 at 11:33
  • @NielsKeurentjes Thanks, I am sure that codes is correct, the problem is I am not sure that my setup is correct. What should I do to run this code in MS Visual C++ 2012? – mans May 23 '13 at 11:35

2 Answers2

3

Put header files after #include "stdafx.h"

#include "stdafx.h"
#include <iostream>
#include <fstream>

stdafx.h must be the first included file, this is Microsoft specific rule.

Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default) 1

masoud
  • 55,379
  • 16
  • 141
  • 208
  • Oh, I already answered same question before, read [this](http://stackoverflow.com/a/16040876/952747). – masoud May 23 '13 at 11:45
2

Your project is probably making use of precompiled headers. If so, the first line of each .cpp file should be:

#include "stdafx.h"

Or whatever the name of the header is.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451