简体   繁体   English

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

[英]C++ ifstream error using string as opening file path

I get this error when I try running the program.What might be the problem as the code is correct as far as I can see. 我尝试运行该程序时收到此错误。据我所知,代码正确无误。

Here is the error 这是错误

std::basic_fstream::basic_fstream(std::string&, const openmode&)' std :: basic_fstream :: basic_fstream(std :: string&,const openmode&)'

Here is the code 这是代码

#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;
}

You could change 你可以改变

fstream inFile(fileName, fstream::in); 

to

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

Although C++11 defines a std::fstream constructor that accepts a std::string as input, Microsoft's implementation of std::fstream apparently does not: 尽管C ++ 11定义了一个std::fstream构造函数,该构造函数接受std::string作为输入,但是Microsoft的std::fstream显然没有:

https://msdn.microsoft.com/en-us/library/a33ahe62.aspx#basic_fstream__basic_fstream https://msdn.microsoft.com/zh-CN/library/a33ahe62.aspx#basic_fstream__basic_fstream

You will have to use the std::string::c_str() method to pass the filename: 您将必须使用std::string::c_str()方法来传递文件名:

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

That being said, consider using std::ifstream instead: 话虽如此,请考虑使用std::ifstream代替:

ifstream inFile(fileName.c_str());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM