問題描述
我正在嘗試讀取文本文件,但沒有任何內容.我覺得它可能沒有在我的 Visual Studio Resources 文件夾中正確鏈接,但是如果我雙擊它 - 它在 Visual Studio 中打開得很好,如果我測試它是否打開或者它是否良好,它不會遇到任何問題.該程序現在可以正常編譯,但沒有輸出.我的命令提示符沒有打印任何內容.有什么建議嗎?
I'm trying to read a text file but nothing is coming out. I feel like maybe It's not linking correctly in my Visual Studio Resources folder but if I double click it - it opens fine in visual studio and it doesn't run into any problems if I test to see if it opens or if it is good. The program compiles fine right now but there's not output. Nothing prints to my command prompt. Any suggestions?
代碼
文本文件
推薦答案
您嘗試按名稱打開沒有路徑的文件,這意味著該文件應在您程序的當前工作目錄中.
You try to open file by name without path, this means the file shall be in current working directory of your program.
問題出在從 VS IDE 運行程序時的當前目錄.默認情況下,VS 將運行程序的當前工作目錄設置為項目目錄 $(ProjectDir)
.但是您的測試文件位于資源目??錄中.所以 open()
函數找不到它,getline()
立即失敗.
The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir)
. But your test file resides in resources directory. So open()
function could not find it and getline()
immediately fails.
解決方案很簡單 - 將您的測試文件復制到項目目錄.或將其復制到目標目錄(創建程序 .exe
文件的位置,通常是 $(ProjectDir)Debug
或 $(ProjectDir)Release
>) 并更改 VS IDE 中的工作目錄設置:Project->Properties->Debugging->Working Directory
,設置為 $(TargetDir).在這種情況下,它將在 IDE 和命令行/Windows 資源管理器中工作.
Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe
file is created, typically $(ProjectDir)Debug
or $(ProjectDir)Release
) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory
, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.
另一種可能的解決方案 - 在 open()
調用中設置正確的文件路徑.出于測試/教育目的,您可以對其進行硬編碼,但實際上這不是一種好的軟件開發風格.
Another possible solution - set correct path to file in your open()
call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.
這篇關于C++ 無法讀取文本文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!