c++ - 如何读写输入文件和输出文件

标签 c++ xcode macos

我正在尝试运行以下程序:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream inFile;
    ofstream outFile;
    double first=1.49, second=2.59, third=3.69, fourth=4.79;
    inFile.open("prices.txt");
    char response;
    if(!inFile.fail())
    {
        cout << "A file by the name prices.txt exists.\n" << "Do you want to continue and overwrite it\n" << " with the new data (y or n);"; cin >> response;
        if(tolower(response) == 'n')
        {
            cout << "The existing file will not be overwritten." << endl;
            return -1;

        }
    }
    outFile.open("prices.txt");
    if (inFile.fail())
    {
        cout << "\n The file does not exist and can not be opened" << endl;
        cout << "The file has been successfully opened for output." << endl;
        outFile << first << "\n" << second << "\n" << fourth << "\n" << endl;
        outFile.close();
        exit(1);
        cout << "The file has been successfully opened for output. " << endl;
        outFile << first << "\n" << second << "\n" << third << "\n" << fourth << endl;
        outFile.close();
        return 0;
    }
}

但是该程序不会将值写入 prices.txt 文件。如果您运行该程序,一旦它说该文件不存在。第二次运行它说文件已经存在,如果你想覆盖它。问题是搜索我的 Mac,我在任何地方都找不到这个文件。

知道我在 Xcode 中运行它时做错了什么吗?一位 friend 在 Visual Studio 2008 中运行了完全相同的代码,并且运行正常。感谢您的帮助。

最佳答案

您需要为可执行文件设置工作目录,因为您假设数据文件位于当前工作目录中。在 Xcode 3.x 中,您可以在可执行文件的 Get Info 的第一个选项卡中设置它。在 Xcode 4.x 中它被移动了,但原理是一样的。

或者,您可以更改数据文件路径(例如,使它们成为绝对路径),这样您就不会对当前工作目录做出假设。

关于c++ - 如何读写输入文件和输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979328/

相关文章:

macos - NSDragOperation通用含义

macos - 使用 Bash 解析 ifconfig 以获取当前 IP 地址(wifi 或以太网)

C++ 格式化输入 : how to 'skip' tokens?

xcode - 每个构建目标本地化 InfoPlist.strings

c++ - 直接在从 .png 加载的 CImage 上绘制时设置文本颜色

ios - 如何删除警告 : Large title font text style before iOS 11. 0 [5]

ios - Xcode/ios : How do you get name of image after letting user select one and displaying it?

macos - 如何将admob广告添加到Xamarin IOS

c++ - << 运算符重载和模板特化

c++ - 随机访问迭代器和双端队列