C 使用字符串作为打开文件路径的ifstream错误
C++ ifstream error using string as opening file path
我尝试运行程序时会遇到此错误。问题可能是什么,因为我可以看到代码正确。
这是错误
std :: basic_fstream :: basic_fstream(std :: string&,const openMode&)'
这是代码
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string fileName;
int frequencyArray[26];
char character;
for (int i = 0; i < 26; i++)
frequencyArray[i] = 0;
cout << "Please enter the name of file: ";
getline(cin, fileName);
fstream inFile(fileName, fstream::in); // to read the file
if (inFile.is_open())
{
while (inFile >> noskipws >> character)
{
// if alphabet
if (isalpha(character))
{
frequencyArray[(int)toupper(character) - 65]++;
}
}
inFile.close();
cout << "Letter frequencies are as: " << endl;
for (int i = 0; i < 26; i++)
{
cout << (char)(i + 65) << " = " << frequencyArray[i] << endl;
}
}
else
{
cout << "Invalid File. Exiting...";
}
return 0;
}
您可以更改
fstream inFile(fileName, fstream::in);
to
fstream inFile(fileName.c_str(), fstream::in);
尽管C 11定义了接受std::string
作为输入的std::fstream
构造函数,但Microsoft的std::fstream
的实现显然没有:
https://msdn.microsoft.com/en-us/library/a33ahe62.aspx#basic_fstream__basic_fstream
您将必须使用std::string::c_str()
方法通过文件名:
fstream inFile(fileName.c_str(), fstream::in);
话虽如此,请考虑使用std::ifstream
:
ifstream inFile(fileName.c_str());
相关文章:
- 如何将更多文件夹添加到c++include路径
- 从函数角度看ID到文件路径的内部与外部映射
- 在C++中设置基于操作系统的文件路径
- C++17 文件系统::remove_all 带有通配符路径
- 从 C 中的变量获取文件的路径,C++
- 将共享库的搜索路径更改为生成文件中提供的 rpath
- 修改生成文件以简化框架 #include 路径
- 将Visual Studio Code路径设置为.clang_format文件
- Windows 非 ASCII 文件路径
- 非 ASCII 文件路径窗口
- C++和带有国家符号的文件路径(也许用 UTF8 编码)
- 获取 H5::D ataSet 的hid_t和文件中的路径以使用 H5OCopy
- 在特定 Unicode 路径中创建文件
- 如何让用户在 tinyxml2 中输入 XML 文件的路径
- 如何将COM .tlb文件导入具有相对路径C++文件中?
- C++ 路径文件存在限制为 260 个字符
- QT-在pro中指定DLL路径.文件
- 路径文件存在导致链接器错误 2028/2019
- 选择QTableWidgetItem qt的路径文件
- 如何有一个正确的路径文件读取它到stringstream