簡體   English   中英

嘗試在 C++ 中創建並寫入 txt 文件

[英]Trying creating and writing into a txt file in C++

基本上,我正在學習一個關於在 C++ 中處理文件的簡單教程。 我一直在嘗試同時創建和寫入 txt 文件,但是我嘗試過的任何方法實際上都不會在我的可執行位置創建 txt 文件。 我還應該說,我打印 myfile.is_open() 只是為了知道文件是否真正創建和打開,但每次使用每種方法我都會得到 0。 我究竟做錯了什么 ? 我主要嘗試創建並寫入這樣的 txt 文件:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream myfile;
    myfile.open("example.txt", ios::out);
    cout << myfile.is_open() << endl;
    myfile << "Writing this to a file.\n";
    myfile.close();
}

首先,我敢打賭您使用的是像 Visual Studio 這樣的 IDE。 大多數 IDE 將您的工作目錄設置在項目目錄之外的某個位置。 我不使用 Visual Studio,但他們中的許多人將它們放在 ../.

所以你的文件正在生成,但不是你認為應該找到它的地方。

如果您在沒有 IDE 的情況下編譯和運行該程序,您將在您期望的位置獲得您的文件。

您還可以告訴 IDE 工作目錄應該是您的項目目錄。


現在,為了避免你養成一些壞習慣,我要再告訴你兩件事。

using namespace std被認為是錯誤的。 相反,我只對那些我將經常使用的東西using語句。 在你的短代碼中,我不會做任何事情。

接下來,如果你要寫出一個文件,最好使用std::ofstream。 否則是相同的代碼。 但更清楚一點的是,您只是將文件用於輸出。

所以我的代碼版本:

#include <iostream>
#include <fstream>

int main()
{
    std::ofstream myfile;
    myfile.open("example.txt");
    std::cout << myfile.is_open() << std::endl;
    myfile << "Writing this to a file.\n";
    myfile.close();
}

是的,那些 std:: 到處都可能很煩人,所以你可以這樣做:

#include <iostream>
#include <fstream>

using std::ofstream;
using std::cout;
using std::endl;

int main()
{
    ofstream myfile;
    myfile.open("example.txt");
    cout << myfile.is_open() << endl;
    myfile << "Writing this to a file.\n";
    myfile.close();
}

實際上,我有一個 CommonUsing.h 的包含,我幾乎在所有地方都放了一些我做的事情。

#pragma once

#include <chrono>
#include <iostream>

#include <date/date.h>

//======================================================================
// The most common using statements I do in most of my code.
//======================================================================

using std::cout;
using std::cerr;
using std::endl;
using std::string;

using namespace std::chrono_literals;

using date::operator<<;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM