Sublime Text,当我在Mac上使用fstream写入文件时,我的文件存储在主文件夹中

问题描述 投票:0回答:1

我在Mac上使用Sublime Text 3编写C ++。我写了一些代码,获取名称和年龄的cin值,并将它们写在文件file.txt中。

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

int main()
{
    string name;
    int age;
    ofstream file("file.txt", ios::out);
    cout<<"enter name: "<<endl;
    cin>>name;
    cout<<"enter age: "<<endl;
    cin>>age;
    file<<name<<" "<<age<<endl;
    return 0;
}

问题是“ file.txt”文件存储在我的主文件夹中,而不是我当前的工作目录中。如何将其存储在当前工作目录中?check this

c++ macos sublimetext3 sublimetext fstream
1个回答
0
投票

这太奇怪了,我对MacOS并不是100%完全确定,但这在Linux和Windows上都可以。

#include <iostream>
#include <fstream>

int main(void) {
    std::ofstream file("./file.txt", std::ios::out); // --- here add './' prefix
    std::string name;
    int age;

    std::cout << "Enter your name: ";
    std::getline(std::cin, name); // use std::getline() for whitespaces

    std::cout << "Your age: ";
    std::cin >> age;

    file << name << ' ' << age << '\n';

    return 0;
}

仅在文件名前添加./以显式定义文件的输出目录必须与程序实际运行的位置相同。

© www.soinside.com 2019 - 2024. All rights reserved.