[英]Reading from text file is not working C++
我只是想從文件中讀取文本,但不知道為什么代碼不起作用。 我已經在運行程序的文件夾中放置了正確的文本文件名。 我一定是在做一些小事。 請在下面的代碼中突出顯示問題:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include<cstdio>
using namespace std;
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
std::string get_working_path() {
char cwd[1024];
if (GetCurrentDir(cwd, sizeof(cwd)) != NULL)
return std::string(cwd);
else
return std::string("");
}
int main() {
string line;
//ofstream myfile;
//myfile.open("cmesymbols.txt", ios::out | ios::app | ios::binary);
ifstream myfile("cmd.txt");
if (myfile.is_open()) {
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else
std::cout << "File not found in cwd: " << get_working_path();
myfile.close();
return 0;
}
輸出:在 cwd 中找不到文件:
ifstream myfile("cmd.txt");
不會為您創建文件。
因此,請確保文件“cmd.txt”與 main.cpp 一起存在於您的項目目錄中
(或主要源文件)。
這段代碼工作正常。 我發現機器中的文件夾設置是隱藏文件的已知擴展名。 我故意將名稱設為“cmd.txt”,但實際名稱顯示為“cmd.txt.txt”,並且由於此代碼未找到此文件。
我將文件名更正為“cmd.txt”,代碼現在正在運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.