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

标签 c++ c++11 visual-c++

当我尝试运行该程序时出现此错误。可能是什么问题,因为据我所知,代码是正确的。

这里是错误

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

fstream inFile(fileName.c_str(), fstream::in);

关于使用字符串作为打开文件路径的 C++ ifstream 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42710345/

相关文章:

c++ - 如何使用 tilemap 将纹理坐标完美映射到 tile?

c++ - 应用GUI开发平台

C++ 右值引用请求

c++ - 信号处理程序异步安全功能

c++ - Windows api 中是否有 O(1) 方式来连接 2 个文件?

c++ - VS2010的concurency runtime和unbounded_buffer<shared_ptr<T>>,有什么坑吗?

c++ - 将 STL 容器传递给 C 函数的指南

c++ - 在处理模板时,如何避免在函数头和函数体中两次声明相同的类型?

c++ - 使用普通异常类有什么意义?

由于 memcpy,C++ ifstream::read 变慢