簡體   English   中英

如何從 c++ 中的文件讀入 [暫停]

[英]How do I read in from a file in c++ [on hold]

我無法從文件中讀取字符。 當此代碼運行時,它說它無法從文件中讀取。 該文本文件與 main.cpp 位於同一文件夾中(不確定這是否有問題)。

char read_from_file;

std::cout << "You picked a pre-written file to play against" << std::endl;
std::cout << "A pre determined choice has been picked, what do you choose?" << std::endl;

std::ifstream inFile;
inFile.open("rps.txt");
inFile >> read_from_file;

if (inFile.is_open())
{
   std::cout << "Successful" << std::endl;
}
else
{
   std::cout << "Unable to open file" << std::endl;
}
inFile.close();

嘗試“rps.txt”的完整路徑。 它應該工作。

聽起來您已經有了這個,但為了完整起見,您要讀取的文件應該與可執行文件位於同一目錄中。

dir
  |- main.cpp
  |- rps.txt
  |- a.out*

* or whatever the name of your program is

我只是在我的 rps.txt 文件中放了一個“R”。 你的代碼大多是好的。 有一個關鍵區別,那就是您需要在嘗試打開文件后立即檢查您是否打開了該文件。 在嘗試讀取之前,您需要知道它是否已打開。

#include <iostream>
#include <fstream>

int main()
{
    char read_from_file;

    std::cout << "You picked a pre-written file to play against" << std::endl;
    std::cout << "A pre determined choice has been picked, what do you choose?" << std::endl;

    std::ifstream inFile;
    inFile.open("rps.txt");
    if (!inFile.is_open())  // You would probably flesh this out with an error
        return 1;           // message or something

    inFile >> read_from_file;

    if (inFile.is_open())
        std::cout << "Successful" << std::endl;
    else
        std::cout << "Unable to open file" << std::endl;
    inFile.close();
}

這對我來說很好。 您沒有具體說明您的錯誤消息是什么。 您是從代碼中收到“無法打開文件”,還是收到系統消息? 該解決方案很可能確保文件可以被讀取,也可以被執行。 為了安全起見,您可以從終端運行chmod 777 rps.txt * 以授予對文件的完全權限。

我還要評論說,因為我所有的ifelse語句都只是單個語句,所以我可以安全地省略{ } 如果您需要一個塊來做不止一件事,請帶回花括號,如果較大塊的一個分支需要花括號,那么所有分支都應該獲取它們以保持一致性/可讀性。

* Linux 和 macOS。 您可以右鍵單擊 Windows 中的文件並在那里設置權限。 也可能是 PowerShell,但我沒有關於 go 的最模糊的方法。

暫無
暫無

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

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