【问题标题】:Why I am getting this error in c++ code为什么我在 C++ 代码中收到此错误
【发布时间】:2013-05-23 11:27:18
【问题描述】:

我有这个简单的代码:

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

但是我得到了很多错误? 如:

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

等等。

我在文件开头有这些定义

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

我在控制台应用程序上使用 VS2012。

编辑1:

完整代码如下:

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


 }

我还注意到我有以下警告:

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

【问题讨论】:

  • 你能把代码贴在std::ifstream ifs;之前吗?可能您之前在某个地方漏掉了一个分号。
  • 在全面使用 std:: 时放弃“使用命名空间 std”这一行
  • Your code works fine。你有没有把代码包装在一个函数中?
  • @NielsKeurentjes 谢谢,我确信代码是正确的,问题是我不确定我的设置是否正确。我应该怎么做才能在 MS Visual C++ 2012 中运行此代码?

标签: c++ visual-c++ stl precompiled-headers


【解决方案1】:

将头文件放在#include "stdafx.h"之后

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

stdafx.h 必须是第一个包含的文件,这是 Microsoft 特定的规则。

Visual C++ 在#include "stdafx.h" 之前不会编译任何东西 源文件,除非编译选项 /Yu'stdafx.h' 未选中 (默认)1

【讨论】:

  • 哦,我之前已经回答过同样的问题,请阅读this
【解决方案2】:

您的项目可能正在使用预编译的头文件。如果是这样,每个.cpp 文件的第一行应该是:

#include "stdafx.h"

或者任何标题的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多