C 使用字符串作为打开文件路径的ifstream错误

C++ ifstream error using string as opening file path

本文关键字:路径 文件 ifstream 错误 字符串      更新时间:2023-10-16

我尝试运行程序时会遇到此错误。问题可能是什么,因为我可以看到代码正确。

这是错误

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());