在VS2010(C++,Win32)中进行文件写入

31 浏览
0 Comments

在VS2010(C++,Win32)中进行文件写入

我之前问过这个问题,你告诉我提到错误,所以我现在会提到它们(我无法弄清楚如何继续我之前开始的线程,我只看到一个“添加评论”按钮和一个“回答你的问题”按钮,所以我不得不更正问题并再次提问,对此我很抱歉):

我的问题如下:

我正在使用Visual Studio 2010编写一个Win32应用程序(不是控制台应用程序)。

我需要知道如何从这个应用程序中写入文件。

我包含了这些头文件:windows.h,stdlib.h,string.h和tchar.h。

我写了一个非常简单的hello world应用程序,它运行得很好。

但是当我尝试在我的项目中包含iostream和fstream时,编译器给了我以下错误。

1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib(21): error C2039: 'abort' : is not a member of '`global namespace''
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib(21): error C2873: 'abort' : symbol cannot be used in a using-declaration
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib(24): error C2039: 'exit' : is not a member of '`global namespace''
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib(24): error C2873: 'exit' : symbol cannot be used in a using-declaration
IntelliSense: the global scope has no "abort"   c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib  21  13  
IntelliSense: the global scope has no "exit"    c:\program files (x86)\microsoft visual studio 10.0\vc\include\cstdlib  24  13  

而当我包含fstream.h时,我得到:

error C1083: Cannot open include file: 'fstream.h': No such file or directory   c:\users\user\documents\visual studio 2010\projects\helloworld\helloworld\main.cpp  5   1   helloworld
IntelliSense: cannot open source file "fstream.h" c:\users\user\documents\visual studio 2010\projects\helloworld\helloworld\main.cpp    5   1   helloworld

iostream.h也是同样的情况

为什么会出现这些错误?

0
0 Comments

问题的原因是在使用Microsoft编译器时,#include "stdafx.h"应该是.cpp文件中的第一个包含的头文件,其他的头文件应该在它之后包含。

解决方法是将#include "stdafx.h"放在.cpp文件的最前面,并在它之后包含其他的头文件。

示例代码如下:

#include "stdafx.h"
#include 
// ... 其他头文件
int main(...) {
    // 代码逻辑
}

通过按照上述方法重新排列头文件的包含顺序,可以解决这个问题。这是在使用Microsoft编译器时一个相当常见的错误。更多相关信息可以参考C++ cout gives undeclared identifier

0
0 Comments

在VS2010中,可能出现了“file writing in vs2010 (c++, win32)”问题。这个问题的出现原因是你可能错误地写了`#include "iostream"`而不是正确的`#include `。解决方法是将错误的代码行改为正确的代码行,即将`#include "iostream"`改为`#include `。这样就可以解决这个问题了。

0
0 Comments

在VS2010中进行C++文件写入时出现了问题。问题的原因是使用了错误的头文件。在C++中,应该使用<cstdlib>代替<stdlib.h><cstring>代替<string.h>(假设你指的是C风格字符串)。如果你想要使用C++的std::string,应该使用<string>,不要加.h后缀。此外,应该使用<fstream>,而不是<fstream.h>

解决这个问题的方法很简单,只需要将错误的头文件替换为正确的头文件即可。将<stdlib.h>替换为<cstdlib><string.h>替换为<cstring><fstream.h>替换为<fstream>

修正后的代码示例:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
int main() {
    std::ofstream file("example.txt");
    if (file.is_open()) {
        file << "This is a test." << std::endl;
        file.close();
    }
    else {
        std::cout << "Unable to open file." << std::endl;
    }
    return 0;
}

通过使用正确的头文件,问题得到了解决。现在,可以在VS2010中进行文件写入操作了。

0